问:
How to append a "1" bit to the front of a binary integer in c#
At the current moment I am trying to figure out a way to append a "1" bit to the front of a binary 32 bit integer, but only in front of the active bits. For example, "101" would turn into "1101", and 000 000 would turn into "1 000 000". Each binary integer would essentially be turned into triplets.

The reason I am wanting to do this is to implement a Hashed Octree with morton encoding. I am mainly attempting to follow this article here: https://geidav.wordpress.com/2014/08/18/advanced-octrees-2-node-representations/

In this article, it references adding a flag "1" bit to the front of morton code with its children in order to distinguish its location code from other location codes.

My Current Code is this:

```<code>
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Collections;

using static Unity.Mathematics.math;

using Unity.Mathematics;

public struct Octree
{
    NativeHashMap<int, OctreeNode> octreeNodes;

    OctreeNode GetParentNode(OctreeNode node)
    {
        int locCodeParent = node.LocCode >> 3;
        return LookupNode(locCodeParent);

    }

    OctreeNode LookupNode(int LocCode)
    {
        OctreeNode node;

        if(!octreeNodes.TryGetValue(LocCode, out node))
        {
            Debug.Log("You done oofed dude, the octree node could not be found with the LocCode provided, please try again or stay oofed");
        }

        return node;

    }

    int GetNodeTreeDepth(OctreeNode node)
    {

        return (int)log2(node.LocCode)/3;

    }

}

public struct OctreeNode
{
    public int LocCode;
}

</code>```

答:
The LongFlags class below will maintain a (64-bit) set of ulong bit flags, as an abstraction. You can query the bits that are set, including querying the highest-set bit.

Your code does not show specifics; but you seem to want to be able to add a bit before another already set bit:

"101" would turn into "1101"

and also a not-set bit:

000 000 would turn into "1 000 000"

Perhaps you would keep track of an int value of your highest "Current" bit; and then use this class to set the next bit ... You can set and clear any individual bits.

For example, you could wrap the below LongFlags in a helper like this:

```<code>    /// <summary>
    /// Helper for bit flags, that tracks a <see cref="CurrentBit"/>.
    /// The <see cref="BitLimit"/> is limited to sixty-four.
    /// Bit positions are numbered from one to sixty-four,
    /// right-to-left (lsb is one, msb is 64).
    /// </summary>
    [DataContract]
    public class BitHelper
    {
        [DataMember]
        private LongFlags longFlags = new LongFlags();

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="bitLimit">Required: sets <see cref="BitLimit"/>.</param>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        public BitHelper(int bitLimit)
        {
            if ((bitLimit < 1)
                    || (bitLimit > 64))
                throw new ArgumentOutOfRangeException(nameof(bitLimit), bitLimit, @"[1, 64]");
            BitLimit = bitLimit;
        }

        /// <summary>
        /// Limits the highest bit that can be set. [1, 64].
        /// (Bit positions are numbered from one to a maximum of sixty-four,
        /// right-to-left (lsb is one, msb is 64).)
        /// </summary>
        [DataMember]
        public int BitLimit { get; private set; }

        /// <summary>
        /// Identifies the current working bit position.
        /// Defaults to one. Ranges: [1, BitLimit].
        /// (Bit positions are numbered from one to a maximum of sixty-four,
        /// right-to-left (lsb is one, msb is 64).)
        /// </summary>
        [DataMember]
        public int CurrentBit { get; private set; } = 1;

        /// <summary>
        /// Returns the state of the <see cref="CurrentBit"/>.
        /// </summary>
        /// <returns>True if one, false if zero.</returns>
        public bool IsCurrentBitSet
            => longFlags[CurrentBit];

        /// <summary>
        /// Increments the <see cref="CurrentBit"/>,
        /// making no changes to bit values.
        /// </summary>
        /// <returns>This object for chaining.</returns>
        /// <exception cref="InvalidOperationException">If the <see cref="CurrentBit"/>
        /// is already at the <see cref="BitLimit"/>.</exception>
        public BitHelper IncrementCurrentBit()
        {
            if (CurrentBit >= BitLimit)
                throw new InvalidOperationException(BitLimit.ToString());
            ++CurrentBit;
            return this;
        }

        /// <summary>
        /// Sets the <see cref="CurrentBit"/> to one.
        /// </summary>
        /// <returns>This object for chaining.</returns>
        public BitHelper SetCurrentBit()
        {
            longFlags.Set(CurrentBit);
            return this;
        }

        /// <summary>
        /// Sets the <see cref="CurrentBit"/> to zero.
        /// </summary>
        /// <returns>This object for chaining.</returns>
        public BitHelper ClearCurrentBit()
        {
            longFlags.Clear(CurrentBit);
            return this;
        }

        /// <summary>
        /// Inverts the value of the <see cref="CurrentBit"/>.
        /// </summary>
        /// <returns>This object for chaining.</returns>
        public BitHelper InvertCurrentBit()
        {
            longFlags[CurrentBit] = !longFlags[CurrentBit];
            return this;
        }

        /// <summary>
        /// Returns the position of the highest bit that is set:
        /// [0, BitLimit]. Returns zero if no bits are set.
        /// </summary>
        public int HighestSetBit
            => longFlags.HighestFlag;

        /// <summary>
        /// Returns all 64 bits as a ULong.
        /// </summary>
        /// <returns>All 64 bits, unsigned.</returns>
        public ulong ToULong()
            => longFlags.Flags;

        /// <summary>
        /// Returns all 64 bits as a Long.
        /// </summary>
        /// <returns>All 64 bits, signed.</returns>
        public long ToLong()
            => (long)longFlags.Flags;

        /// <summary>
        /// Returns the lower 32 bits as a UInt
        /// --- REGARDLESS of the setting of <see cref="BitLimit"/>.
        /// </summary>
        /// <returns>The lower 32 bits, unsigned.</returns>
        public uint ToUInt()
            => (uint)longFlags.Flags;

        /// <summary>
        /// Returns the lower 32 bits as an Int
        /// --- REGARDLESS of the setting of <see cref="BitLimit"/>.
        /// </summary>
        /// <returns>The lower 32 bits, signed.</returns>
        public int ToInt()
            => (int)longFlags.Flags;

        /// <summary>
        /// Returns the lower 16 bits as a UShort
        /// --- REGARDLESS of the setting of <see cref="BitLimit"/>.
        /// </summary>
        /// <returns>The lower 16 bits, unsigned.</returns>
        public ushort ToUShort()
            => (ushort)longFlags.Flags;

        /// <summary>
        /// Returns the lower 16 bits as a short
        /// --- REGARDLESS of the setting of <see cref="BitLimit"/>.
        /// </summary>
        /// <returns>The lower 16 bits, signed.</returns>
        public short ToShort()
            => (short)longFlags.Flags;

        /// <summary>
        /// Returns the lower 8 bits as a Byte
        /// --- REGARDLESS of the setting of <see cref="BitLimit"/>.
        /// </summary>
        /// <returns>The lower 8 bits, unsigned.</returns>
        public byte ToByte()
            => (byte)longFlags.Flags;

        /// <summary>
        /// Returns the lower 8 bits as an SByte
        /// --- REGARDLESS of the setting of <see cref="BitLimit"/>.
        /// </summary>
        /// <returns>The lower 8 bits, signed.</returns>
        public sbyte ToSByte()
            => (sbyte)longFlags.Flags;
    }
</code>```

Here is LongFlags:

```using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;

namespace Sc.Util.System
{
    ///
    /// A class holding <see langword="ulong"/> bit <see cref="Flags"/>.
    /// Flags are numbered from one to sixty-four, from right-to-left in the
    /// <see langword="ulong"/> value --- but the abstraction allows you to
    /// ignore that as an implementation detail. This class implements
    /// methods to set and clear flags, and set and clear flags from other
    /// instances. This also implements implicit conversions to and from
    /// <see langword="ulong"/> --- and therefore you may invoke methods with
    /// <see langword="ulong"/> values. This is also
    /// <see cref="IXmlSerializable"/> and <see cref="ICloneable"/>.
    ///
    [Serializable]
    public sealed class LongFlags
            : ICloneable,
                    IXmlSerializable
    {
        ///
        /// Counts the bits that are set on the argument.
        ///
        /// <param name="flags">Arbitrary.</param>
        /// <returns>A count of bits that are set.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static int CountBits(ulong flags)
        {
            int result = 0;
            for (int i = 0; i < 64; ++i) {
                if ((flags & 1) == 1)
                    ++result;
                flags >>= 1;
            }
            return result;
        }

        ///
        /// Returns the <see langword="ulong"/> VALUE of the SINGLE
        /// highest bit that is set on the argument.
        ///
        /// <param name="flags">Arbitrary.</param>
        /// <returns>The value of the single highest bit that is set.
        /// Returns zero if no bits are set.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static ulong GetHighestBitValue(ulong flags)
        {
            int highestBit = LongFlags.GetHighestBitPosition(flags);
            return highestBit == 0
                    ? 0UL
                    : 1UL << (highestBit - 1);
        }

        ///
        /// Returns the <see langword="ulong"/> VALUE of the SINGLE
        /// lowest bit that is set on the argument.
        ///
        /// <param name="flags">Arbitrary.</param>
        /// <returns>The value of the single lowest bit that is set.
        /// Returns zero if no bits are set.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static ulong GetLowestBitValue(ulong flags)
        {
            int lowestBit = LongFlags.GetLowestBitPosition(flags);
            return lowestBit == 0
                    ? 0UL
                    : 1UL << (lowestBit - 1);
        }

        ///
        /// Returns the position of highest bit that is set on the argument:
        /// where the right-most bit is position one; and the left-most is sixty-four.
        ///
        /// <param name="flags">Arbitrary.</param>
        /// <returns>The position of the highest bit that is set.
        /// Returns zero if no bits are set.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static int GetHighestBitPosition(ulong flags)
        {
            if (flags == 0UL)
                return 0;
            for (int i = 63; i >= 0; --i) {
                if (((flags >> i) & 1) == 1)
                    return i + 1;
            }
            Debug.Fail($"Value is '{flags}' but iteration failed to find a set bit.");
            return 0;
        }

        ///
        /// Returns the position of lowest bit that is set on the argument:
        /// where the right-most bit is position one; and the left-most is sixty-four.
        ///
        /// <param name="flags">Arbitrary.</param>
        /// <returns>The position of the lowest bit that is set.
        /// Returns zero if no bits are set.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static int GetLowestBitPosition(ulong flags)
        {
            if (flags == 0UL)
                return 0;
            for (int i = 0; i < 64; ++i) {
                if (((flags >> i) & 1) == 1)
                    return i + 1;
            }
            Debug.Fail($"Value is '{flags}' but iteration failed to find a set bit.");
            return 0;
        }

        ///
        /// Returns a new value from the <paramref name="flags"/>
        /// with the <paramref name="predicate"/> removed.
        ///
        /// <param name="flags">Arbitrary.</param>
        /// <param name="predicate">Arbitrary.</param>
        /// <returns>Returns <paramref name="flags"/> <c>&</c> the
        /// complement of the <paramref name="predicate"/>.</returns>
        public static ulong Excluding(ulong flags, ulong predicate)
            => flags & ~predicate;

        ///
        /// Returns true if the <paramref name="source"/> has ANY of the bits that
        /// are set on the <paramref name="flags"/>. Notice that if the
        /// <paramref name="flags"/> are zero, this will return false.
        ///
        /// <param name="source">The source flags.
        /// If zero, this will return false.</param>
        /// <param name="flags">Arbitrary bits to search for.
        /// If zero, this will return false.</param>
        /// <returns>True if ANY <The name="flags"/> are present on the
        /// <paramref name="source"/> (and at least one flags bit is set).</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static bool HasAnyBits(ulong source, ulong flags)
            => (source & flags) != 0UL;

        ///
        /// Returns true if the <paramref name="source"/> has ALL of the bits that
        /// are set on the <paramref name="flags"/>. Notice that if the
        /// <paramref name="flags"/> are zero, this will return false.
        ///
        /// <param name="source">The source flags.
        /// If zero, this will return false.</param>
        /// <param name="flags">Arbitrary bits to search for.
        /// If zero, this will return false.</param>
        /// <returns>True if ALL <The name="flags"/> are present on the
        /// <paramref name="source"/> (and at least one flags bit is set).</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static bool HasAllBits(ulong source, ulong flags)
            => (flags != 0UL) && ((source & flags) == flags);

        ///
        /// Returns true if the <paramref name="source"/> has ONLY bits that are set
        /// on the <paramref name="flags"/> --- false if any bit is set on the source
        /// that is not defined on the flags. Notice that if the
        /// <paramref name="flags"/> are zero, this will return false.
        ///
        /// <param name="source">The source flags.
        /// If zero, this will return false.</param>
        /// <param name="flags">Arbitrary bits to search for.
        /// If zero, this will return false.</param>
        /// <param name="requiresAll">If true, then <paramref name="source"/>
        /// MUST contain ALL <paramref name="flags"/> AND NO other bits.
        /// If false, the source may contain zero or more bits
        /// present on the flags --- and no bits that are not present on the flags
        /// (source need not contain all, but can only contain a bit on the flags).</param>
        /// <returns>True if only the flags are present on the source --- false if any bit is
        /// set on th source that is not defined on the flags.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static bool HasOnlyBits(ulong source, ulong flags, bool requiresAll)
            => (flags != 0UL)
                    && (source != 0UL)
                    && ((source & ~flags) == 0UL)
                    && (!requiresAll
                    || ((source & flags) == flags));

        ///
        /// Returns true if the <paramref name="source"/> has NONE of the
        /// bits that are set on <paramref name="flags"/>. Notice that if the
        /// <paramref name="flags"/> are zero, this will return TRUE.
        ///
        /// <param name="source">The source flags.
        /// If zero, this will return true.</param>
        /// <param name="flags">Arbitrary flags to search for.
        /// If zero, this will return true.</param>
        /// <returns>True if no flags bits are set here.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static bool HasNoBits(ulong source, ulong flags)
            => (source & flags) == 0UL;

        ///
        /// Checks the range.
        ///
        /// <param name="position">[1,64].</param>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private static void rangeCheckPosition(int position)
        {
            if ((position <= 0)
                    || (position > 64))
                throw new ArgumentOutOfRangeException(nameof(position), position, @"[1,64]");
        }

        ///
        /// Default constructor creates an empty instance.
        ///
        public LongFlags() { }

        ///
        /// Creates a new instance with each flag position in the argument array set.
        ///
        /// <param name="flags">The flags to set.</param>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        public LongFlags(params int[] flags)
            => Set(flags);

        ///
        /// Creates a new instance with the given bits set.
        ///
        /// <param name="flags">The bits to copy. This directly
        /// sets <see cref="Flags"/>.</param>
        public LongFlags(ulong flags)
            => Flags = flags;

        ///
        /// Creates a deep clone of the argument.
        ///
        /// <param name="clone">The value to copy.</param>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private LongFlags(LongFlags clone)
            => Flags = clone.Flags;

        XmlSchema IXmlSerializable.GetSchema()
            => null;

        void IXmlSerializable.WriteXml(XmlWriter writer)
            => writer.WriteString(Flags.ToString(CultureInfo.InvariantCulture));

        void IXmlSerializable.ReadXml(XmlReader reader)
        {
            if (reader.IsEmptyElement)
                Flags = 0UL;
            else {
                reader.Read();
                switch (reader.NodeType) {
                    case XmlNodeType.EndElement :
                        Flags = 0UL; // empty after all...
                        break;
                    case XmlNodeType.Text :
                    case XmlNodeType.CDATA :
                        Flags = ulong.Parse(reader.ReadContentAsString(), CultureInfo.InvariantCulture);
                        break;
                    default :
                        throw new InvalidOperationException("Expected text/cdata");
                }
            }
        }

        ///
        /// The current bit flags. Flags are numbered from one to sixty-four: where
        /// the right-most bit is one, and the left-most is sixty four.
        /// Methods do not require knowledge of the flag positions; and flags
        /// are simply numbered [1,64].
        ///
        public ulong Flags
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get;
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            private set;
        }

        ///
        /// An indexer that gets or sets a boolean indicating if the flag at the
        /// given <paramref name="position"/> is set.
        ///
        /// <param name="position">[1,64].</param>
        /// <returns>True if the flag is set.</returns>
        public bool this[int position]
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get => IsSet(position);
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            set {
                if (value)
                    Set(position);
                else
                    Clear(position);
            }
        }

        ///
        /// Returns true if the flag at the given position is set.
        ///
        /// <param name="position">The position to test: [1,64].</param>
        /// <returns>True if the flag is set.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public bool IsSet(int position)
        {
            LongFlags.rangeCheckPosition(position);
            return LongFlags.HasAnyBits(Flags, 1UL << (position - 1));
        }

        ///
        /// Returns true if each flag in the argument array is set.
        /// This will return FALSE if none are provided.
        ///
        /// <param name="positions">[1,64].</param>
        /// <returns>True if all provided flags are set. NOTICE: this will
        /// return FALSE if none are provided.</returns>
        public bool IsAllSet(params int[] positions)
        {
            if (positions.Length == 0)
                return false;
            foreach (int position in positions) {
                if (!IsSet(position))
                    return false;
            }
            return true;
        }

        ///
        /// Returns true if ANY flag in the argument array is set.
        /// This will return FALSE if none are provided.
        ///
        /// <param name="positions">[1,64].</param>
        /// <returns>True if ANY provided flag is set; AND if AT LEAST ONE
        /// is provided.</returns>
        public bool IsAnySet(params int[] positions)
        {
            foreach (int position in positions) {
                if (IsSet(position))
                    return true;
            }
            return false;
        }

        ///
        /// Returns true if all flags are set.
        ///
        public bool IsFull
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get => Flags == ulong.MaxValue;
        }

        ///
        /// Returns true if no flags are set.
        ///
        public bool IsEmpty
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get => Flags == 0UL;
        }

        ///
        /// Counts the flags that are set.
        ///
        /// <returns>A count of <see cref="Flags"/> bits that are set.</returns>
        public int Count
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get => LongFlags.CountBits(Flags);
        }

        ///
        /// Returns the position of highest flag that is set.
        ///
        /// <returns>The position of the highest bit that is set on <see cref="Flags"/>.</returns>
        public int HighestFlag
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get => LongFlags.GetHighestBitPosition(Flags);
        }

        ///
        /// Returns the position of lowest flag that is set.
        ///
        /// <returns>The position of the lowest bit that is set on <see cref="Flags"/>.</returns>
        public int LowestFlag
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get => LongFlags.GetLowestBitPosition(Flags);
        }

        ///
        /// Returns the <see langword="ulong"/> VALUE of the SINGLE
        /// highest bit that is set.
        ///
        /// <returns>The value of the single highest bit that is set on <see cref="Flags"/>.</returns>
        public ulong HighestFlagValue
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get => LongFlags.GetHighestBitValue(Flags);
        }

        ///
        /// Returns the <see langword="ulong"/> VALUE of the SINGLE
        /// lowest bit that is set.
        ///
        /// <returns>The value of the single lowest bit that is set on <see cref="Flags"/>.</returns>
        public ulong LowestFlagValue
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get => LongFlags.GetLowestBitValue(Flags);
        }

        ///
        /// Sets the flag at the position specified by the argument.
        ///
        /// <param name="position">[1,64].</param>
        /// <returns>This object for chaining.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LongFlags Set(int position)
        {
            LongFlags.rangeCheckPosition(position);
            Flags |= 1UL << (position - 1);
            return this;
        }

        ///
        /// Sets the flag at each specified position.
        ///
        /// <param name="positions">[1,64].</param>
        /// <returns>This object for chaining.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LongFlags Set(params int[] positions)
        {
            ulong flags = Flags;
            try {
                foreach (int position in positions) {
                    Set(position);
                }
                return this;
            } catch {
                Flags = flags;
                throw;
            }
        }

        ///
        /// Sets all flags to one.
        ///
        /// <returns>This object for chaining.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LongFlags SetAll()
        {
            Flags = ulong.MaxValue;
            return this;
        }

        ///
        /// Clears the flag at the position specified by the argument.
        ///
        /// <param name="position">[1,64].</param>
        /// <returns>This object for chaining.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LongFlags Clear(int position)
        {
            LongFlags.rangeCheckPosition(position);
            Flags &= ~(1UL << (position - 1));
            return this;
        }

        ///
        /// Clears the flag at each position specified in the argument array.
        ///
        /// <param name="positions">[1,64].</param>
        /// <returns>This object for chaining.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LongFlags Clear(params int[] positions)
        {
            ulong flags = Flags;
            try {
                foreach (int position in positions) {
                    Clear(position);
                }
                return this;
            } catch {
                Flags = flags;
                throw;
            }
        }

        ///
        /// Resets all <see cref="Flags"/> to zero.
        ///
        /// <returns>This object for chaining.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LongFlags Clear()
        {
            Flags = 0UL;
            return this;
        }

        ///
        /// Sets <see cref="Flags"/> to the argument's value.
        ///
        /// <param name="clone">The value to copy.</param>
        /// <returns>This object for chaining.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LongFlags SetFrom(LongFlags clone)
        {
            Flags = clone.Flags;
            return this;
        }

        ///
        /// Sets <see cref="Flags"/> to the argument's value.
        ///
        /// <param name="clone">The value to copy.</param>
        /// <returns>This object for chaining.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LongFlags SetFrom(ulong clone)
        {
            Flags = clone;
            return this;
        }

        ///
        /// Adds all of the flags in the argument to this instance.
        ///
        /// <param name="flags">Arbitrary flags to add.</param>
        /// <returns>This object for chaining.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LongFlags AddAllFlags(LongFlags flags)
        {
            Flags |= flags.Flags;
            return this;
        }

        ///
        /// Removes all flags defined on the argument from this instance.
        ///
        /// <param name="flags">Arbitrary flags to remove.</param>
        /// <returns>This object for chaining.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LongFlags RemoveAllFlags(LongFlags flags)
        {
            Flags &= ~flags.Flags;
            return this;
        }

        ///
        /// Returns true if this instance has ANY of the <see cref="Flags"/>
        /// defined on the argument. Notice that if the
        /// <paramref name="flags"/> are zero, this will return false.
        ///
        /// <param name="flags">Arbitrary flags to search for.</param>
        /// <returns>True if any flags are present here
        /// (and at least one flag bit is set).</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public bool HasAny(LongFlags flags)
            => LongFlags.HasAnyBits(Flags, flags.Flags);

        ///
        /// Returns true if this instance has ALL of the <see cref="Flags"/>
        /// defined on the argument. Notice that if the
        /// <paramref name="flags"/> are zero, this will return false.
        ///
        /// <param name="flags">Arbitrary flags to search for.</param>
        /// <returns>True if ALL flags are present here
        /// (and at least one flag bit is set).</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public bool HasAll(LongFlags flags)
            => LongFlags.HasAllBits(Flags, flags.Flags);

        ///
        /// Returns true if this instance has ONLY flags that are set
        /// on the <paramref name="flags"/> --- false if any flag is set here
        /// that is not defined on the flags. Notice that if the
        /// <paramref name="flags"/> are zero, this will return false
        /// --- and if this <see cref="Flags"/> is zero this returns false.
        ///
        /// <param name="flags">Arbitrary flags to search for.
        /// If zero, this will return false.</param>
        /// <param name="requiresAll">If true, then this
        /// MUST contain ALL <paramref name="flags"/> AND NO other flags.
        /// If false, this may contain zero or more flags
        /// present on the flags --- and no flags that are not present on the flags
        /// (this need not contain all, but can only contain a flag on the flags).</param>
        /// <returns>True if only the flags are present here --- false if any flag is
        /// set here that is not defined on the flags.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public bool HasOnly(LongFlags flags, bool requiresAll)
            => LongFlags.HasOnlyBits(Flags, flags.Flags, requiresAll);

        ///
        /// Returns true if this instance has NONE of the <see cref="Flags"/>
        /// defined on the argument.
        ///
        /// <param name="flags">Arbitrary.</param>
        /// <returns>True if no flags are present here.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public bool HasNone(LongFlags flags)
            => LongFlags.HasNoBits(Flags, flags.Flags);

        ///
        /// Returns a deep clone of this object.
        ///
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LongFlags Clone()
            => new LongFlags(this);

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        object ICloneable.Clone()
            => Clone();

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static implicit operator ulong(LongFlags longFlags)
            => longFlags.Flags;

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static implicit operator LongFlags(ulong flags)
            => new LongFlags(flags);

        public override string ToString()
            => $"{nameof(LongFlags)}"
                    + "["
                    + $"{Convert.ToString((byte)(Flags >> 56), 2)}"
                    + $" {Convert.ToString((byte)(Flags >> 48), 2)}"
                    + $" {Convert.ToString((byte)(Flags >> 40), 2)}"
                    + $" {Convert.ToString((byte)(Flags >> 32), 2)}"
                    + $" {Convert.ToString((byte)(Flags >> 24), 2)}"
                    + $" {Convert.ToString((byte)(Flags >> 16), 2)}"
                    + $" {Convert.ToString((byte)(Flags >> 8), 2)}"
                    + $" {Convert.ToString((byte)Flags, 2)}"
                    + "]";
    }
}
```

Body:
At the current moment I am trying to figure out a way to append a "1" bit to the front of a binary 32 bit integer, but only in front of the active bits. For example, "101" would turn into "1101", and 000 000 would turn into "1 000 000". Each binary integer would essentially be turned into triplets.

The reason I am wanting to do this is to implement a Hashed Octree with morton encoding. I am mainly attempting to follow this article here: https://geidav.wordpress.com/2014/08/18/advanced-octrees-2-node-representations/

In this article, it references adding a flag "1" bit to the front of morton code with its children in order to distinguish its location code from other location codes.

My Current Code is this:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Collections;

using static Unity.Mathematics.math;

using Unity.Mathematics;

public struct Octree
{
    NativeHashMap<int, OctreeNode> octreeNodes;

    OctreeNode GetParentNode(OctreeNode node)
    {
        int locCodeParent = node.LocCode >> 3;
        return LookupNode(locCodeParent);

    }

    OctreeNode LookupNode(int LocCode)
    {
        OctreeNode node;

        if(!octreeNodes.TryGetValue(LocCode, out node))
        {
            Debug.Log("You done oofed dude, the octree node could not be found with the LocCode provided, please try again or stay oofed");
        }

        return node;

    }

    int GetNodeTreeDepth(OctreeNode node)
    {

        return (int)log2(node.LocCode)/3;

    }

}

public struct OctreeNode
{
    public int LocCode;
}

Body:
The LongFlags class below will maintain a (64-bit) set of ulong bit flags, as an abstraction. You can query the bits that are set, including querying the highest-set bit.

Your code does not show specifics; but you seem to want to be able to add a bit before another already set bit:

"101" would turn into "1101"

and also a not-set bit:

000 000 would turn into "1 000 000"

Perhaps you would keep track of an int value of your highest "Current" bit; and then use this class to set the next bit ... You can set and clear any individual bits.

For example, you could wrap the below LongFlags in a helper like this:

    /// <summary>
    /// Helper for bit flags, that tracks a <see cref="CurrentBit"/>.
    /// The <see cref="BitLimit"/> is limited to sixty-four.
    /// Bit positions are numbered from one to sixty-four,
    /// right-to-left (lsb is one, msb is 64).
    /// </summary>
    [DataContract]
    public class BitHelper
    {
        [DataMember]
        private LongFlags longFlags = new LongFlags();

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="bitLimit">Required: sets <see cref="BitLimit"/>.</param>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        public BitHelper(int bitLimit)
        {
            if ((bitLimit < 1)
                    || (bitLimit > 64))
                throw new ArgumentOutOfRangeException(nameof(bitLimit), bitLimit, @"[1, 64]");
            BitLimit = bitLimit;
        }

        /// <summary>
        /// Limits the highest bit that can be set. [1, 64].
        /// (Bit positions are numbered from one to a maximum of sixty-four,
        /// right-to-left (lsb is one, msb is 64).)
        /// </summary>
        [DataMember]
        public int BitLimit { get; private set; }

        /// <summary>
        /// Identifies the current working bit position.
        /// Defaults to one. Ranges: [1, BitLimit].
        /// (Bit positions are numbered from one to a maximum of sixty-four,
        /// right-to-left (lsb is one, msb is 64).)
        /// </summary>
        [DataMember]
        public int CurrentBit { get; private set; } = 1;

        /// <summary>
        /// Returns the state of the <see cref="CurrentBit"/>.
        /// </summary>
        /// <returns>True if one, false if zero.</returns>
        public bool IsCurrentBitSet
            => longFlags[CurrentBit];

        /// <summary>
        /// Increments the <see cref="CurrentBit"/>,
        /// making no changes to bit values.
        /// </summary>
        /// <returns>This object for chaining.</returns>
        /// <exception cref="InvalidOperationException">If the <see cref="CurrentBit"/>
        /// is already at the <see cref="BitLimit"/>.</exception>
        public BitHelper IncrementCurrentBit()
        {
            if (CurrentBit >= BitLimit)
                throw new InvalidOperationException(BitLimit.ToString());
            ++CurrentBit;
            return this;
        }

        /// <summary>
        /// Sets the <see cref="CurrentBit"/> to one.
        /// </summary>
        /// <returns>This object for chaining.</returns>
        public BitHelper SetCurrentBit()
        {
            longFlags.Set(CurrentBit);
            return this;
        }

        /// <summary>
        /// Sets the <see cref="CurrentBit"/> to zero.
        /// </summary>
        /// <returns>This object for chaining.</returns>
        public BitHelper ClearCurrentBit()
        {
            longFlags.Clear(CurrentBit);
            return this;
        }

        /// <summary>
        /// Inverts the value of the <see cref="CurrentBit"/>.
        /// </summary>
        /// <returns>This object for chaining.</returns>
        public BitHelper InvertCurrentBit()
        {
            longFlags[CurrentBit] = !longFlags[CurrentBit];
            return this;
        }

        /// <summary>
        /// Returns the position of the highest bit that is set:
        /// [0, BitLimit]. Returns zero if no bits are set.
        /// </summary>
        public int HighestSetBit
            => longFlags.HighestFlag;

        /// <summary>
        /// Returns all 64 bits as a ULong.
        /// </summary>
        /// <returns>All 64 bits, unsigned.</returns>
        public ulong ToULong()
            => longFlags.Flags;

        /// <summary>
        /// Returns all 64 bits as a Long.
        /// </summary>
        /// <returns>All 64 bits, signed.</returns>
        public long ToLong()
            => (long)longFlags.Flags;

        /// <summary>
        /// Returns the lower 32 bits as a UInt
        /// --- REGARDLESS of the setting of <see cref="BitLimit"/>.
        /// </summary>
        /// <returns>The lower 32 bits, unsigned.</returns>
        public uint ToUInt()
            => (uint)longFlags.Flags;

        /// <summary>
        /// Returns the lower 32 bits as an Int
        /// --- REGARDLESS of the setting of <see cref="BitLimit"/>.
        /// </summary>
        /// <returns>The lower 32 bits, signed.</returns>
        public int ToInt()
            => (int)longFlags.Flags;

        /// <summary>
        /// Returns the lower 16 bits as a UShort
        /// --- REGARDLESS of the setting of <see cref="BitLimit"/>.
        /// </summary>
        /// <returns>The lower 16 bits, unsigned.</returns>
        public ushort ToUShort()
            => (ushort)longFlags.Flags;

        /// <summary>
        /// Returns the lower 16 bits as a short
        /// --- REGARDLESS of the setting of <see cref="BitLimit"/>.
        /// </summary>
        /// <returns>The lower 16 bits, signed.</returns>
        public short ToShort()
            => (short)longFlags.Flags;

        /// <summary>
        /// Returns the lower 8 bits as a Byte
        /// --- REGARDLESS of the setting of <see cref="BitLimit"/>.
        /// </summary>
        /// <returns>The lower 8 bits, unsigned.</returns>
        public byte ToByte()
            => (byte)longFlags.Flags;

        /// <summary>
        /// Returns the lower 8 bits as an SByte
        /// --- REGARDLESS of the setting of <see cref="BitLimit"/>.
        /// </summary>
        /// <returns>The lower 8 bits, signed.</returns>
        public sbyte ToSByte()
            => (sbyte)longFlags.Flags;
    }

Here is LongFlags:

using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;

namespace Sc.Util.System
{
    /// <summary>
    /// A class holding <see langword="ulong"/> bit <see cref="Flags"/>.
    /// Flags are numbered from one to sixty-four, from right-to-left in the
    /// <see langword="ulong"/> value --- but the abstraction allows you to
    /// ignore that as an implementation detail. This class implements
    /// methods to set and clear flags, and set and clear flags from other
    /// instances. This also implements implicit conversions to and from
    /// <see langword="ulong"/> --- and therefore you may invoke methods with
    /// <see langword="ulong"/> values. This is also
    /// <see cref="IXmlSerializable"/> and <see cref="ICloneable"/>.
    /// </summary>
    [Serializable]
    public sealed class LongFlags
            : ICloneable,
                    IXmlSerializable
    {
        /// <summary>
        /// Counts the bits that are set on the argument.
        /// </summary>
        /// <param name="flags">Arbitrary.</param>
        /// <returns>A count of bits that are set.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static int CountBits(ulong flags)
        {
            int result = 0;
            for (int i = 0; i < 64; ++i) {
                if ((flags & 1) == 1)
                    ++result;
                flags >>= 1;
            }
            return result;
        }

        /// <summary>
        /// Returns the <see langword="ulong"/> VALUE of the SINGLE
        /// highest bit that is set on the argument.
        /// </summary>
        /// <param name="flags">Arbitrary.</param>
        /// <returns>The value of the single highest bit that is set.
        /// Returns zero if no bits are set.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static ulong GetHighestBitValue(ulong flags)
        {
            int highestBit = LongFlags.GetHighestBitPosition(flags);
            return highestBit == 0
                    ? 0UL
                    : 1UL << (highestBit - 1);
        }

        /// <summary>
        /// Returns the <see langword="ulong"/> VALUE of the SINGLE
        /// lowest bit that is set on the argument.
        /// </summary>
        /// <param name="flags">Arbitrary.</param>
        /// <returns>The value of the single lowest bit that is set.
        /// Returns zero if no bits are set.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static ulong GetLowestBitValue(ulong flags)
        {
            int lowestBit = LongFlags.GetLowestBitPosition(flags);
            return lowestBit == 0
                    ? 0UL
                    : 1UL << (lowestBit - 1);
        }

        /// <summary>
        /// Returns the position of highest bit that is set on the argument:
        /// where the right-most bit is position one; and the left-most is sixty-four.
        /// </summary>
        /// <param name="flags">Arbitrary.</param>
        /// <returns>The position of the highest bit that is set.
        /// Returns zero if no bits are set.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static int GetHighestBitPosition(ulong flags)
        {
            if (flags == 0UL)
                return 0;
            for (int i = 63; i >= 0; --i) {
                if (((flags >> i) & 1) == 1)
                    return i + 1;
            }
            Debug.Fail($"Value is '{flags}' but iteration failed to find a set bit.");
            return 0;
        }

        /// <summary>
        /// Returns the position of lowest bit that is set on the argument:
        /// where the right-most bit is position one; and the left-most is sixty-four.
        /// </summary>
        /// <param name="flags">Arbitrary.</param>
        /// <returns>The position of the lowest bit that is set.
        /// Returns zero if no bits are set.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static int GetLowestBitPosition(ulong flags)
        {
            if (flags == 0UL)
                return 0;
            for (int i = 0; i < 64; ++i) {
                if (((flags >> i) & 1) == 1)
                    return i + 1;
            }
            Debug.Fail($"Value is '{flags}' but iteration failed to find a set bit.");
            return 0;
        }

        /// <summary>
        /// Returns a new value from the <paramref name="flags"/>
        /// with the <paramref name="predicate"/> removed.
        /// </summary>
        /// <param name="flags">Arbitrary.</param>
        /// <param name="predicate">Arbitrary.</param>
        /// <returns>Returns <paramref name="flags"/> <c>&</c> the
        /// complement of the <paramref name="predicate"/>.</returns>
        public static ulong Excluding(ulong flags, ulong predicate)
            => flags & ~predicate;

        /// <summary>
        /// Returns true if the <paramref name="source"/> has ANY of the bits that
        /// are set on the <paramref name="flags"/>. Notice that if the
        /// <paramref name="flags"/> are zero, this will return false.
        /// </summary>
        /// <param name="source">The source flags.
        /// If zero, this will return false.</param>
        /// <param name="flags">Arbitrary bits to search for.
        /// If zero, this will return false.</param>
        /// <returns>True if ANY <The name="flags"/> are present on the
        /// <paramref name="source"/> (and at least one flags bit is set).</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static bool HasAnyBits(ulong source, ulong flags)
            => (source & flags) != 0UL;

        /// <summary>
        /// Returns true if the <paramref name="source"/> has ALL of the bits that
        /// are set on the <paramref name="flags"/>. Notice that if the
        /// <paramref name="flags"/> are zero, this will return false.
        /// </summary>
        /// <param name="source">The source flags.
        /// If zero, this will return false.</param>
        /// <param name="flags">Arbitrary bits to search for.
        /// If zero, this will return false.</param>
        /// <returns>True if ALL <The name="flags"/> are present on the
        /// <paramref name="source"/> (and at least one flags bit is set).</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static bool HasAllBits(ulong source, ulong flags)
            => (flags != 0UL) && ((source & flags) == flags);

        /// <summary>
        /// Returns true if the <paramref name="source"/> has ONLY bits that are set
        /// on the <paramref name="flags"/> --- false if any bit is set on the source
        /// that is not defined on the flags. Notice that if the
        /// <paramref name="flags"/> are zero, this will return false.
        /// </summary>
        /// <param name="source">The source flags.
        /// If zero, this will return false.</param>
        /// <param name="flags">Arbitrary bits to search for.
        /// If zero, this will return false.</param>
        /// <param name="requiresAll">If true, then <paramref name="source"/>
        /// MUST contain ALL <paramref name="flags"/> AND NO other bits.
        /// If false, the source may contain zero or more bits
        /// present on the flags --- and no bits that are not present on the flags
        /// (source need not contain all, but can only contain a bit on the flags).</param>
        /// <returns>True if only the flags are present on the source --- false if any bit is
        /// set on th source that is not defined on the flags.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static bool HasOnlyBits(ulong source, ulong flags, bool requiresAll)
            => (flags != 0UL)
                    && (source != 0UL)
                    && ((source & ~flags) == 0UL)
                    && (!requiresAll
                    || ((source & flags) == flags));

        /// <summary>
        /// Returns true if the <paramref name="source"/> has NONE of the
        /// bits that are set on <paramref name="flags"/>. Notice that if the
        /// <paramref name="flags"/> are zero, this will return TRUE.
        /// </summary>
        /// <param name="source">The source flags.
        /// If zero, this will return true.</param>
        /// <param name="flags">Arbitrary flags to search for.
        /// If zero, this will return true.</param>
        /// <returns>True if no flags bits are set here.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static bool HasNoBits(ulong source, ulong flags)
            => (source & flags) == 0UL;

        /// <summary>
        /// Checks the range.
        /// </summary>
        /// <param name="position">[1,64].</param>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private static void rangeCheckPosition(int position)
        {
            if ((position <= 0)
                    || (position > 64))
                throw new ArgumentOutOfRangeException(nameof(position), position, @"[1,64]");
        }

        /// <summary>
        /// Default constructor creates an empty instance.
        /// </summary>
        public LongFlags() { }

        /// <summary>
        /// Creates a new instance with each flag position in the argument array set.
        /// </summary>
        /// <param name="flags">The flags to set.</param>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        public LongFlags(params int[] flags)
            => Set(flags);

        /// <summary>
        /// Creates a new instance with the given bits set.
        /// </summary>
        /// <param name="flags">The bits to copy. This directly
        /// sets <see cref="Flags"/>.</param>
        public LongFlags(ulong flags)
            => Flags = flags;

        /// <summary>
        /// Creates a deep clone of the argument.
        /// </summary>
        /// <param name="clone">The value to copy.</param>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private LongFlags(LongFlags clone)
            => Flags = clone.Flags;

        XmlSchema IXmlSerializable.GetSchema()
            => null;

        void IXmlSerializable.WriteXml(XmlWriter writer)
            => writer.WriteString(Flags.ToString(CultureInfo.InvariantCulture));

        void IXmlSerializable.ReadXml(XmlReader reader)
        {
            if (reader.IsEmptyElement)
                Flags = 0UL;
            else {
                reader.Read();
                switch (reader.NodeType) {
                    case XmlNodeType.EndElement :
                        Flags = 0UL; // empty after all...
                        break;
                    case XmlNodeType.Text :
                    case XmlNodeType.CDATA :
                        Flags = ulong.Parse(reader.ReadContentAsString(), CultureInfo.InvariantCulture);
                        break;
                    default :
                        throw new InvalidOperationException("Expected text/cdata");
                }
            }
        }

        /// <summary>
        /// The current bit flags. Flags are numbered from one to sixty-four: where
        /// the right-most bit is one, and the left-most is sixty four.
        /// Methods do not require knowledge of the flag positions; and flags
        /// are simply numbered [1,64].
        /// </summary>
        public ulong Flags
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get;
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            private set;
        }

        /// <summary>
        /// An indexer that gets or sets a boolean indicating if the flag at the
        /// given <paramref name="position"/> is set.
        /// </summary>
        /// <param name="position">[1,64].</param>
        /// <returns>True if the flag is set.</returns>
        public bool this[int position]
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get => IsSet(position);
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            set {
                if (value)
                    Set(position);
                else
                    Clear(position);
            }
        }

        /// <summary>
        /// Returns true if the flag at the given position is set.
        /// </summary>
        /// <param name="position">The position to test: [1,64].</param>
        /// <returns>True if the flag is set.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public bool IsSet(int position)
        {
            LongFlags.rangeCheckPosition(position);
            return LongFlags.HasAnyBits(Flags, 1UL << (position - 1));
        }

        /// <summary>
        /// Returns true if each flag in the argument array is set.
        /// This will return FALSE if none are provided.
        /// </summary>
        /// <param name="positions">[1,64].</param>
        /// <returns>True if all provided flags are set. NOTICE: this will
        /// return FALSE if none are provided.</returns>
        public bool IsAllSet(params int[] positions)
        {
            if (positions.Length == 0)
                return false;
            foreach (int position in positions) {
                if (!IsSet(position))
                    return false;
            }
            return true;
        }

        /// <summary>
        /// Returns true if ANY flag in the argument array is set.
        /// This will return FALSE if none are provided.
        /// </summary>
        /// <param name="positions">[1,64].</param>
        /// <returns>True if ANY provided flag is set; AND if AT LEAST ONE
        /// is provided.</returns>
        public bool IsAnySet(params int[] positions)
        {
            foreach (int position in positions) {
                if (IsSet(position))
                    return true;
            }
            return false;
        }

        /// <summary>
        /// Returns true if all flags are set.
        /// </summary>
        public bool IsFull
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get => Flags == ulong.MaxValue;
        }

        /// <summary>
        /// Returns true if no flags are set.
        /// </summary>
        public bool IsEmpty
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get => Flags == 0UL;
        }

        /// <summary>
        /// Counts the flags that are set.
        /// </summary>
        /// <returns>A count of <see cref="Flags"/> bits that are set.</returns>
        public int Count
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get => LongFlags.CountBits(Flags);
        }

        /// <summary>
        /// Returns the position of highest flag that is set.
        /// </summary>
        /// <returns>The position of the highest bit that is set on <see cref="Flags"/>.</returns>
        public int HighestFlag
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get => LongFlags.GetHighestBitPosition(Flags);
        }

        /// <summary>
        /// Returns the position of lowest flag that is set.
        /// </summary>
        /// <returns>The position of the lowest bit that is set on <see cref="Flags"/>.</returns>
        public int LowestFlag
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get => LongFlags.GetLowestBitPosition(Flags);
        }

        /// <summary>
        /// Returns the <see langword="ulong"/> VALUE of the SINGLE
        /// highest bit that is set.
        /// </summary>
        /// <returns>The value of the single highest bit that is set on <see cref="Flags"/>.</returns>
        public ulong HighestFlagValue
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get => LongFlags.GetHighestBitValue(Flags);
        }

        /// <summary>
        /// Returns the <see langword="ulong"/> VALUE of the SINGLE
        /// lowest bit that is set.
        /// </summary>
        /// <returns>The value of the single lowest bit that is set on <see cref="Flags"/>.</returns>
        public ulong LowestFlagValue
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get => LongFlags.GetLowestBitValue(Flags);
        }

        /// <summary>
        /// Sets the flag at the position specified by the argument.
        /// </summary>
        /// <param name="position">[1,64].</param>
        /// <returns>This object for chaining.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LongFlags Set(int position)
        {
            LongFlags.rangeCheckPosition(position);
            Flags |= 1UL << (position - 1);
            return this;
        }

        /// <summary>
        /// Sets the flag at each specified position.
        /// </summary>
        /// <param name="positions">[1,64].</param>
        /// <returns>This object for chaining.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LongFlags Set(params int[] positions)
        {
            ulong flags = Flags;
            try {
                foreach (int position in positions) {
                    Set(position);
                }
                return this;
            } catch {
                Flags = flags;
                throw;
            }
        }

        /// <summary>
        /// Sets all flags to one.
        /// </summary>
        /// <returns>This object for chaining.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LongFlags SetAll()
        {
            Flags = ulong.MaxValue;
            return this;
        }

        /// <summary>
        /// Clears the flag at the position specified by the argument.
        /// </summary>
        /// <param name="position">[1,64].</param>
        /// <returns>This object for chaining.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LongFlags Clear(int position)
        {
            LongFlags.rangeCheckPosition(position);
            Flags &= ~(1UL << (position - 1));
            return this;
        }

        /// <summary>
        /// Clears the flag at each position specified in the argument array.
        /// </summary>
        /// <param name="positions">[1,64].</param>
        /// <returns>This object for chaining.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LongFlags Clear(params int[] positions)
        {
            ulong flags = Flags;
            try {
                foreach (int position in positions) {
                    Clear(position);
                }
                return this;
            } catch {
                Flags = flags;
                throw;
            }
        }

        /// <summary>
        /// Resets all <see cref="Flags"/> to zero.
        /// </summary>
        /// <returns>This object for chaining.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LongFlags Clear()
        {
            Flags = 0UL;
            return this;
        }

        /// <summary>
        /// Sets <see cref="Flags"/> to the argument's value.
        /// </summary>
        /// <param name="clone">The value to copy.</param>
        /// <returns>This object for chaining.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LongFlags SetFrom(LongFlags clone)
        {
            Flags = clone.Flags;
            return this;
        }

        /// <summary>
        /// Sets <see cref="Flags"/> to the argument's value.
        /// </summary>
        /// <param name="clone">The value to copy.</param>
        /// <returns>This object for chaining.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LongFlags SetFrom(ulong clone)
        {
            Flags = clone;
            return this;
        }

        /// <summary>
        /// Adds all of the flags in the argument to this instance.
        /// </summary>
        /// <param name="flags">Arbitrary flags to add.</param>
        /// <returns>This object for chaining.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LongFlags AddAllFlags(LongFlags flags)
        {
            Flags |= flags.Flags;
            return this;
        }

        /// <summary>
        /// Removes all flags defined on the argument from this instance.
        /// </summary>
        /// <param name="flags">Arbitrary flags to remove.</param>
        /// <returns>This object for chaining.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LongFlags RemoveAllFlags(LongFlags flags)
        {
            Flags &= ~flags.Flags;
            return this;
        }

        /// <summary>
        /// Returns true if this instance has ANY of the <see cref="Flags"/>
        /// defined on the argument. Notice that if the
        /// <paramref name="flags"/> are zero, this will return false.
        /// </summary>
        /// <param name="flags">Arbitrary flags to search for.</param>
        /// <returns>True if any flags are present here
        /// (and at least one flag bit is set).</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public bool HasAny(LongFlags flags)
            => LongFlags.HasAnyBits(Flags, flags.Flags);

        /// <summary>
        /// Returns true if this instance has ALL of the <see cref="Flags"/>
        /// defined on the argument. Notice that if the
        /// <paramref name="flags"/> are zero, this will return false.
        /// </summary>
        /// <param name="flags">Arbitrary flags to search for.</param>
        /// <returns>True if ALL flags are present here
        /// (and at least one flag bit is set).</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public bool HasAll(LongFlags flags)
            => LongFlags.HasAllBits(Flags, flags.Flags);

        /// <summary>
        /// Returns true if this instance has ONLY flags that are set
        /// on the <paramref name="flags"/> --- false if any flag is set here
        /// that is not defined on the flags. Notice that if the
        /// <paramref name="flags"/> are zero, this will return false
        /// --- and if this <see cref="Flags"/> is zero this returns false.
        /// </summary>
        /// <param name="flags">Arbitrary flags to search for.
        /// If zero, this will return false.</param>
        /// <param name="requiresAll">If true, then this
        /// MUST contain ALL <paramref name="flags"/> AND NO other flags.
        /// If false, this may contain zero or more flags
        /// present on the flags --- and no flags that are not present on the flags
        /// (this need not contain all, but can only contain a flag on the flags).</param>
        /// <returns>True if only the flags are present here --- false if any flag is
        /// set here that is not defined on the flags.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public bool HasOnly(LongFlags flags, bool requiresAll)
            => LongFlags.HasOnlyBits(Flags, flags.Flags, requiresAll);

        /// <summary>
        /// Returns true if this instance has NONE of the <see cref="Flags"/>
        /// defined on the argument.
        /// </summary>
        /// <param name="flags">Arbitrary.</param>
        /// <returns>True if no flags are present here.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public bool HasNone(LongFlags flags)
            => LongFlags.HasNoBits(Flags, flags.Flags);

        /// <summary>
        /// Returns a deep clone of this object.
        /// </summary>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LongFlags Clone()
            => new LongFlags(this);

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        object ICloneable.Clone()
            => Clone();

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static implicit operator ulong(LongFlags longFlags)
            => longFlags.Flags;

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static implicit operator LongFlags(ulong flags)
            => new LongFlags(flags);

        public override string ToString()
            => $"{nameof(LongFlags)}"
                    + "["
                    + $"{Convert.ToString((byte)(Flags >> 56), 2)}"
                    + $" {Convert.ToString((byte)(Flags >> 48), 2)}"
                    + $" {Convert.ToString((byte)(Flags >> 40), 2)}"
                    + $" {Convert.ToString((byte)(Flags >> 32), 2)}"
                    + $" {Convert.ToString((byte)(Flags >> 24), 2)}"
                    + $" {Convert.ToString((byte)(Flags >> 16), 2)}"
                    + $" {Convert.ToString((byte)(Flags >> 8), 2)}"
                    + $" {Convert.ToString((byte)Flags, 2)}"
                    + "]";
    }
}


来源: stackexchange

问:
How do you auto layout constraint a notification label inside a button?
This is the screenshot of my issue.

My problem is the button label is not a view. I can not anchor that notification label to it. If I anchor that label to any of the sides, the screen size will affect it.

Example: 6s Plus

and iPhone SE

It's fine on the bigger phones.

答: I think the best way is to make a UIView with the badge and the title label in it and just overlay a UIButton with no title. This way you can constraint the badge label and the title label together.</p>

ContentLicense: CC BY-SA 4.0


问:
if user pastes 32 characters into the license text-box first split textbox
if user pastes 32 characters into the license text-box first split textbox, the method  will place 8 characters into each of the 4 text boxes

see
i have 4 text box ... max length (8)

```<code><input type = "text" size = "8" maxlength="32" name = "LicenseNumber1"
id="LicenseNumber1">

<input type = "text" size = "8" maxlength="32" name = "LicenseNumber2"
id="LicenseNumber2">

<input type = "text" size = "8" maxlength="32" name = "LicenseNumber3"
id="LicenseNumber3">

<input type = "text" size = "8" maxlength="32" name = "LicenseNumber4"
id="LicenseNumber4">
</code>```

& my license is 32 characters like 06e1823681f48e2f013904403b33ff08
now if i paste the whole 32 character in my first test box i.e. LicenseNumber1 then i

want other three textbox wil be automatic fill bcause(8*4=32)

答:
Well, here is an example.

It isn't perfect, but it is a good base.

http://jsfiddle.net/mazzzzz/nRHM3/4/

ContentLicense: CC BY-SA 3.0

Body:
if user pastes 32 characters into the license text-box first split textbox, the method  will place 8 characters into each of the 4 text boxes

see
i have 4 text box ... max length (8)

<input type = "text" size = "8" maxlength="32" name = "LicenseNumber1"
id="LicenseNumber1">

<input type = "text" size = "8" maxlength="32" name = "LicenseNumber2"
id="LicenseNumber2">

<input type = "text" size = "8" maxlength="32" name = "LicenseNumber3"
id="LicenseNumber3">

<input type = "text" size = "8" maxlength="32" name = "LicenseNumber4"
id="LicenseNumber4">

& my license is 32 characters like 06e1823681f48e2f013904403b33ff08
now if i paste the whole 32 character in my first test box i.e. LicenseNumber1 then i

want other three textbox wil be automatic fill bcause(8*4=32)


问:
Create a click event on ListViewItem programmatically in WPF
I'm making a WPF app, this app has a UserControl, which has a list view.

I tried to create a click event listener but i never got it to work right, and i havend find anything to solve it

I fill this list view items with an object like this:

```<code>List<AsesoriaClass> listaAsesorias = phpClass.getListaAsesoriasAsesor(asesor.ID);
            foreach (var asesoria in listaAsesorias)
            {
                AsesoriaTable data = new AsesoriaTable(asesoria.AsesoriaID.ToString(), asesoria.ClienteNombre + " " + asesoria.ClienteApellidos, asesoria.FechaInicio.ToString(), asesoria.FechaFinal.ToString());
                this.ListView.Items.Add(data);
            }
</code>```

And this is the XAML of the User Control:

```<code><ListView x:Name="ListView">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="ID" DisplayMemberBinding="{Binding Path=Id}" Width="100"/>
                    <GridViewColumn Header="Cliente" DisplayMemberBinding="{Binding Path=Cliente}" Width="300"/>
                    <GridViewColumn Header="Inicio" DisplayMemberBinding="{Binding Path=Inicio}" Width="200"/>
                    <GridViewColumn Header="Final" DisplayMemberBinding="{Binding Path=Final}" Width="200"/>
                </GridView>
            </ListView.View>
        </ListView>
</code>```

I want to make a click listener so, when i click on an item something happens (to start i just want it to show a mesage box). how do i do this?

答:
You can simply attach an Event Handler on SelectionChanged. Like this

```<code> ListView.SelectionChanged += LstOnSelectionChanged;
</code>```

Where LstOnSelectionChanged is a method.

```<code>private void LstOnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
  MessageBox.Show("Anything");
}
</code>```

Body:
I'm making a WPF app, this app has a UserControl, which has a list view.

I tried to create a click event listener but i never got it to work right, and i havend find anything to solve it

I fill this list view items with an object like this:

List<AsesoriaClass> listaAsesorias = phpClass.getListaAsesoriasAsesor(asesor.ID);
            foreach (var asesoria in listaAsesorias)
            {
                AsesoriaTable data = new AsesoriaTable(asesoria.AsesoriaID.ToString(), asesoria.ClienteNombre + " " + asesoria.ClienteApellidos, asesoria.FechaInicio.ToString(), asesoria.FechaFinal.ToString());
                this.ListView.Items.Add(data);
            }

And this is the XAML of the User Control:

<ListView x:Name="ListView">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="ID" DisplayMemberBinding="{Binding Path=Id}" Width="100"/>
                    <GridViewColumn Header="Cliente" DisplayMemberBinding="{Binding Path=Cliente}" Width="300"/>
                    <GridViewColumn Header="Inicio" DisplayMemberBinding="{Binding Path=Inicio}" Width="200"/>
                    <GridViewColumn Header="Final" DisplayMemberBinding="{Binding Path=Final}" Width="200"/>
                </GridView>
            </ListView.View>
        </ListView>

I want to make a click listener so, when i click on an item something happens (to start i just want it to show a mesage box). how do i do this?

Body:
You can simply attach an Event Handler on SelectionChanged. Like this

 ListView.SelectionChanged += LstOnSelectionChanged;

Where LstOnSelectionChanged is a method.

private void LstOnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
  MessageBox.Show("Anything");
}


问:
GraphQL Prisma database that allows two tables to have relations to one table
I'm looking to have relational tables that connects two different tables to the one table.

```<code>type User {
  booking: [Booking!]! @relation(name: "UserToBooking" onDelete: SET_NULL)
}

type Booking {
  owner: User! @relation(name: "UserToBooking", onDelete: SET_NULL)
  renter: [User!]! @relation(name: "UserToBooking", onDelete: SET_NULL)
}
</code>```

Prisma only allows one of the same relation so having two "UserToBooking" is not possible.  What's the best way to create a relation that allows to do this?

答:
You'd have to have two different booking types. I'm guessing this is something like an AirBnB arrangement where a user can own a property that is rented out and/or also rent properties from others. I think you should specify two different items in your User type to distinguish these, and then have a relationship for these. Something like this:

```<code>type User {
  booking: [Booking!]! @relation(name: "UserToBooking" onDelete: CASCADE)
  let: [Booking!]! @relation(name: "UserToLetBooking" onDelete: CASCADE)
}

type Booking {
  owner: User! @relation(name: "UserToLetBooking", onDelete: SET_NULL)
  renter: User! @relation(name: "UserToBooking", onDelete: SET_NULL)
}
</code>```

This way the booking shows a user who is the letting owner and a user who is the renter. I have also changed the renter in booking to a single user because I figure each booking has 1 letting owner and 1 renter. I also changed the onDelete setting for the user type so that if a user is deleted any of his bookings or lets are also deleted. This would be a typical pattern but is up to you.

Body:
I'm looking to have relational tables that connects two different tables to the one table.

type User {
  booking: [Booking!]! @relation(name: "UserToBooking" onDelete: SET_NULL)
}

type Booking {
  owner: User! @relation(name: "UserToBooking", onDelete: SET_NULL)
  renter: [User!]! @relation(name: "UserToBooking", onDelete: SET_NULL)
}

Prisma only allows one of the same relation so having two "UserToBooking" is not possible.  What's the best way to create a relation that allows to do this?

Body:
You'd have to have two different booking types. I'm guessing this is something like an AirBnB arrangement where a user can own a property that is rented out and/or also rent properties from others. I think you should specify two different items in your User type to distinguish these, and then have a relationship for these. Something like this:

type User {
  booking: [Booking!]! @relation(name: "UserToBooking" onDelete: CASCADE)
  let: [Booking!]! @relation(name: "UserToLetBooking" onDelete: CASCADE)
}

type Booking {
  owner: User! @relation(name: "UserToLetBooking", onDelete: SET_NULL)
  renter: User! @relation(name: "UserToBooking", onDelete: SET_NULL)
}

This way the booking shows a user who is the letting owner and a user who is the renter. I have also changed the renter in booking to a single user because I figure each booking has 1 letting owner and 1 renter. I also changed the onDelete setting for the user type so that if a user is deleted any of his bookings or lets are also deleted. This would be a typical pattern but is up to you.


问:
PDOException (1044) SQLSTATE[HY000] [1044] Access denied for user ''@'localhost' to database 'forge'
I am using Laravel 5 and getting the following exception:

PDOException (1044) SQLSTATE[HY000] [1044] Access denied for user
  ''@'localhost' to database 'forge'

My database configuration file is:

```<code><?php

return [
/*
|--------------------------------------------------------------------------
| PDO Fetch Style
|--------------------------------------------------------------------------
|
| By default, database results will be returned as instances of the PHP
| stdClass object; however, you may desire to retrieve records in an
| array format for simplicity. Here you can tweak the fetch style.
|
*/

'fetch' => PDO::FETCH_CLASS,

/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for all database work. Of course
| you may use many connections at once using the Database library.
|
*/

'default' => 'mysql',

/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Here are each of the database connections setup for your application.
| Of course, examples of configuring each database platform that is
| supported by Laravel is shown below to make development simple.
|
|
| All database work in Laravel is done through the PHP PDO facilities
| so make sure you have the driver for your particular database of
| choice installed on your machine before you begin development.
|
*/

'connections' => [

    'sqlite' => [
        'driver'   => 'sqlite',
        'database' => storage_path().'/database.sqlite',
        'prefix'   => '',
    ],

    'mysql' => [
        'driver'    => 'mysql',
        'host'      => env('DB_HOST', 'localhost'),
        'database'  => env('DB_DATABASE', 'forge'),
        'username'  => env('DB_USERNAME', 'forge'),
        'password'  => env('DB_PASSWORD', ''),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],

    'pgsql' => [
        'driver'   => 'pgsql',
        'host'     => env('DB_HOST', 'localhost'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'charset'  => 'utf8',
        'prefix'   => '',
        'schema'   => 'public',
    ],

    'sqlsrv' => [
        'driver'   => 'sqlsrv',
        'host'     => env('DB_HOST', 'localhost'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'prefix'   => '',
    ],

],

/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk haven't actually been run in the database.
|
*/

'migrations' => 'migrations',

/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer set of commands than a typical key-value systems
| such as APC or Memcached. Laravel makes it easy to dig right in.
|
*/

'redis' => [

    'cluster' => false,

    'default' => [
        'host'     => '127.0.0.1',
        'port'     => 6379,
        'database' => 0,
    ],

    ],

];
</code>```

How can I solve it?

答:
I was getting the same message with empty username. The username was always blank.

The issue was with MySQL. The SQLSTATE error message is being passed directly from MySQL.

So then I deleted the database and user. Re-created the database in the Databases tab of PhpMyAdmin. And importantly separately added the user and privileges. This fixed the issue.

I could connect from the MySQL client and run migrations.

Body:
I am using Laravel 5 and getting the following exception:

PDOException (1044) SQLSTATE[HY000] [1044] Access denied for user
  ''@'localhost' to database 'forge'

My database configuration file is:

<?php

return [
/*
|--------------------------------------------------------------------------
| PDO Fetch Style
|--------------------------------------------------------------------------
|
| By default, database results will be returned as instances of the PHP
| stdClass object; however, you may desire to retrieve records in an
| array format for simplicity. Here you can tweak the fetch style.
|
*/

'fetch' => PDO::FETCH_CLASS,

/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for all database work. Of course
| you may use many connections at once using the Database library.
|
*/

'default' => 'mysql',

/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Here are each of the database connections setup for your application.
| Of course, examples of configuring each database platform that is
| supported by Laravel is shown below to make development simple.
|
|
| All database work in Laravel is done through the PHP PDO facilities
| so make sure you have the driver for your particular database of
| choice installed on your machine before you begin development.
|
*/

'connections' => [

    'sqlite' => [
        'driver'   => 'sqlite',
        'database' => storage_path().'/database.sqlite',
        'prefix'   => '',
    ],

    'mysql' => [
        'driver'    => 'mysql',
        'host'      => env('DB_HOST', 'localhost'),
        'database'  => env('DB_DATABASE', 'forge'),
        'username'  => env('DB_USERNAME', 'forge'),
        'password'  => env('DB_PASSWORD', ''),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],

    'pgsql' => [
        'driver'   => 'pgsql',
        'host'     => env('DB_HOST', 'localhost'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'charset'  => 'utf8',
        'prefix'   => '',
        'schema'   => 'public',
    ],

    'sqlsrv' => [
        'driver'   => 'sqlsrv',
        'host'     => env('DB_HOST', 'localhost'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'prefix'   => '',
    ],

],

/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk haven't actually been run in the database.
|
*/

'migrations' => 'migrations',

/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer set of commands than a typical key-value systems
| such as APC or Memcached. Laravel makes it easy to dig right in.
|
*/

'redis' => [

    'cluster' => false,

    'default' => [
        'host'     => '127.0.0.1',
        'port'     => 6379,
        'database' => 0,
    ],

    ],

];

How can I solve it?


问:
How do I map a resolved promise object in string form onto a button, for example
I understand there are a ton of existing questions that are kind of similar but none of them really were simple enough for my case.

This is the behavior of my promise as of now:

at least on lines 62 and 63, we can see through the console that the exact and correct values are being found. My goal is to either pass that as a value into someVar or otherwise somehow update line 70 with the updated value.

As it stands, my buttons simply render Object [Promise] and don't change after the promise has been resolved.

This is basically my first promise function I've ever written and I'm pretty lost to be honest, despite some detailed explanations from others that I think go beyond what I need to know to construct a simple promise for an api call.

full code:

```<code>import React from 'react';
import {Highlight} from "react-instantsearch-dom";
import Card from '@material-ui/core/Card';
import Typography from '@material-ui/core/Typography';
import Paper from '@material-ui/core/Paper';
import Link from 'next/link';
import {makeStyles} from "@material-ui/styles";
import '../static/default.css';
import algoliasearch from "algoliasearch";

const searchClient = algoliasearch(
    **************************
);

const index = searchClient.initIndex("Parks");

const useStyles = makeStyles({
    root: {
        background: 'linear-gradient(45deg, #4496DB 30%, #5df78e 90%)',
        border: 0,
        fontSize: 16,
        borderRadius: 3,
        boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
        color: 'white',
        height: 48,
        width: "100%",
        padding: '0 30px',
    },
    card: {
        minWidth: 275,
    },
    bullet: {
        display: 'inline-block',
        margin: '0 2px',
        transform: 'scale(0.8)',
    },
    title: {
        fontSize: 14,
    },
    pos: {
        marginBottom: 12,
    },
});

function indexSearch(objId){
    return new Promise((resolve, reject) => {
        index.getObject(objId, ['fullName'], (err, content) => {
            if (content != null){
                resolve(content.fullName);
            }
            else{
                reject(Error());
            }
        });
    });
}

function NewButton({redirectId}){
    const classes = useStyles();
    var someVar = indexSearch(redirectId).then(function(result){
        console.log(result);
        return result;
    }).catch(function rejected() {console.log('rejected')});
    console.log('after' + someVar);
    return(
        <Link as={`/details/${redirectId}`} href={`/details?objectId=${redirectId}`}>
            <a>
                <button type="button" className={classes.root}>
                    {`Learn more about the ${someVar}`}
                </button>
            </a>
        </Link>
    )
}

class Hit extends React.Component{

    render() {
        const props = this.props;
        return(

            <Card>
                <Paper id="paper" square>
                    <Typography id="title" color="textPrimary" variant="h6">
                        <Highlight className="ais-Highlight-header" attribute="fullName" hit={props.hit}/>
                        <Highlight className="ais-Highlight-state" attribute="states" hit={props.hit}/>
                    </Typography>
                </Paper>
                <Paper square>
                    <Typography color="textSecondary" variant="h6">
                        <Highlight attribute="description" hit={props.hit}/>
                    </Typography>
                </Paper>
                <NewButton redirectId={props.hit.objectID}/>
            </Card>
        )
    }
}

export default Hit;
</code>```

答:
Rendering a component is synchronous. If you want to do something asynchronous you'll need a state variable in your component. On the first render it will be empty, and you might render some placeholder view such as a loading spinner. You'll then kick off the async stuff, and when it completes you set state causing it to render again.</p>

```<code>function NewButton({redirectId}){
  const classes = useStyles();
  const [someVar, setSomeVar] = useState(null);

  useEffect(() => {
    indexSearch(redirectId).then(result => {
      setSomeVar(result);
    })
  }, [])

  if (!someVar) {
    return null;
  }

  return(
      <Link as={`/details/${redirectId}`} href={`/details?objectId=${redirectId}`}>
          <a>
              <button type="button" className={classes.root}>
                  {`Learn more about the ${someVar}`}
              </button>
          </a>
      </Link>
  )
}
</code>```

Body:
I understand there are a ton of existing questions that are kind of similar but none of them really were simple enough for my case.

This is the behavior of my promise as of now:

at least on lines 62 and 63, we can see through the console that the exact and correct values are being found. My goal is to either pass that as a value into someVar or otherwise somehow update line 70 with the updated value.

As it stands, my buttons simply render Object [Promise] and don't change after the promise has been resolved.

This is basically my first promise function I've ever written and I'm pretty lost to be honest, despite some detailed explanations from others that I think go beyond what I need to know to construct a simple promise for an api call.

full code:

import React from 'react';
import {Highlight} from "react-instantsearch-dom";
import Card from '@material-ui/core/Card';
import Typography from '@material-ui/core/Typography';
import Paper from '@material-ui/core/Paper';
import Link from 'next/link';
import {makeStyles} from "@material-ui/styles";
import '../static/default.css';
import algoliasearch from "algoliasearch";

const searchClient = algoliasearch(
    **************************
);

const index = searchClient.initIndex("Parks");

const useStyles = makeStyles({
    root: {
        background: 'linear-gradient(45deg, #4496DB 30%, #5df78e 90%)',
        border: 0,
        fontSize: 16,
        borderRadius: 3,
        boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
        color: 'white',
        height: 48,
        width: "100%",
        padding: '0 30px',
    },
    card: {
        minWidth: 275,
    },
    bullet: {
        display: 'inline-block',
        margin: '0 2px',
        transform: 'scale(0.8)',
    },
    title: {
        fontSize: 14,
    },
    pos: {
        marginBottom: 12,
    },
});

function indexSearch(objId){
    return new Promise((resolve, reject) => {
        index.getObject(objId, ['fullName'], (err, content) => {
            if (content != null){
                resolve(content.fullName);
            }
            else{
                reject(Error());
            }
        });
    });
}

function NewButton({redirectId}){
    const classes = useStyles();
    var someVar = indexSearch(redirectId).then(function(result){
        console.log(result);
        return result;
    }).catch(function rejected() {console.log('rejected')});
    console.log('after' + someVar);
    return(
        <Link as={`/details/${redirectId}`} href={`/details?objectId=${redirectId}`}>

                <button type="button" className={classes.root}>
                    {`Learn more about the ${someVar}`}
                </button>

        </Link>
    )
}

class Hit extends React.Component{

    render() {
        const props = this.props;
        return(

            <Card>
                <Paper id="paper" square>
                    <Typography id="title" color="textPrimary" variant="h6">
                        <Highlight className="ais-Highlight-header" attribute="fullName" hit={props.hit}/>
                        <Highlight className="ais-Highlight-state" attribute="states" hit={props.hit}/>
                    </Typography>
                </Paper>
                <Paper square>
                    <Typography color="textSecondary" variant="h6">
                        <Highlight attribute="description" hit={props.hit}/>
                    </Typography>
                </Paper>
                <NewButton redirectId={props.hit.objectID}/>
            </Card>
        )
    }
}

export default Hit;

Body:
Rendering a component is synchronous. If you want to do something asynchronous you'll need a state variable in your component. On the first render it will be empty, and you might render some placeholder view such as a loading spinner. You'll then kick off the async stuff, and when it completes you set state causing it to render again.

function NewButton({redirectId}){
  const classes = useStyles();
  const [someVar, setSomeVar] = useState(null);

  useEffect(() => {
    indexSearch(redirectId).then(result => {
      setSomeVar(result);
    })
  }, [])

  if (!someVar) {
    return null;
  }

  return(
      <Link as={`/details/${redirectId}`} href={`/details?objectId=${redirectId}`}>
          <a>
              <button type="button" className={classes.root}>
                  {`Learn more about the ${someVar}`}
              </button>
          </a>
      </Link>
  )
}


问:
Using WriteProcessMemory() in C++ with Multilevel Pointers and Offsets?
One of the parameters for WriteProcessMemory() obviously asks for a pointer to the base address. But what if it is a multilevel pointer?  For example, let's say I had to find a pointer 3 times to finally get the static address and the first offset was 0, the second was 57 and the third was 268.  Now if I wanted to write to that exact location, how would I include the offsets into the WriteProcessMemory() function and do I have to include all three offsets or only the last one that led me to the static address? To clarify things, I am basically practicing manipulating memory on a first person shooter game on PC. My goal isn't really to make hacks or anything. I just wanted to practice writing memory into a process. (For example, I would try to write new values into the 'health' address or the 'ammo' address.) And I just mainly want to know how to account for the offsets in a multilevel pointer.

答:
You cannot "include" the offsets in a call to WriteProcessMemory() to walk a chain of pointers.  A multilevel pointer or pointer chain is a pointer that points to a pointer that points to a pointer.  In most cases there are relative offsets that must be added after each pointer is de referenced.

WriteProcessMemory just writes to a single address, it is singular in purpose.

But you must de-reference each pointer and add the offset.  To do this, you must use ReadProcessMemory.  You can use this function to walk the pointer chain, it will dereference each pointer and add the offset correctly:

uintptr_t FindDMAAddy(HANDLE hProc, uintptr_t ptr, std::vector<unsigned int> offsets)
{
    for (unsigned int i = 0; i < offsets.size(); ++i)
    {
        ReadProcessMemory(hProc, (BYTE*)ptr, &ptr, sizeof(ptr), 0);
        ptr += offsets[i];
    }
    return ptr;
}
```

<p>An example of calling the function looks like:</p>

```uintptr_t ammoAddr = FindDMAAddy(hProcess, dynamicPtrBaseAddr, { 0x374, 0x14, 0x0 });
```

The result of this function will be the address of the variable you want to read or write.  All that's left to do is a subsequent call to ReadProcessMemory or WriteProcessMemory depending what you want to do.

Body:
You cannot "include" the offsets in a call to WriteProcessMemory() to walk a chain of pointers.  A multilevel pointer or pointer chain is a pointer that points to a pointer that points to a pointer.  In most cases there are relative offsets that must be added after each pointer is de referenced.

WriteProcessMemory just writes to a single address, it is singular in purpose.

But you must de-reference each pointer and add the offset.  To do this, you must use ReadProcessMemory.  You can use this function to walk the pointer chain, it will dereference each pointer and add the offset correctly:

uintptr_t FindDMAAddy(HANDLE hProc, uintptr_t ptr, std::vector<unsigned int> offsets)
{
    for (unsigned int i = 0; i < offsets.size(); ++i)
    {
        ReadProcessMemory(hProc, (BYTE*)ptr, &ptr, sizeof(ptr), 0);
        ptr += offsets[i];
    }
    return ptr;
}

An example of calling the function looks like:

uintptr_t ammoAddr = FindDMAAddy(hProcess, dynamicPtrBaseAddr, { 0x374, 0x14, 0x0 });

The result of this function will be the address of the variable you want to read or write.  All that's left to do is a subsequent call to ReadProcessMemory or WriteProcessMemory depending what you want to do.