Search code examples
c#bit

C# hexadecimal to struct


I have different kinds of hexadecimals with a length of 8, like FFFFFFFA (4 bytes 255, 255, 255 and 250 ASCII encoded). Converting this one to binary gives: 11111111 11111111 11111111 11111010 where every digits stands for true (1) or false (0).

It would be nice to have some kind of object in C# where every property represent a binary. In this case a object with 32 bool properties.

Searching on the internet brought me to structs but I can't figure out how to do it.

Concrete questions: How can I convert hexadecimals to a struct and back?

Any direction would be nice!

Thanks in advance!


Solution

  • Thank you for all the comments and samples. I ended up with using BitVector32 because it's more efficient for boolean values and small integers (memory and performance overhead for more info: https://learn.microsoft.com/en-us/dotnet/api/system.collections.specialized.bitvector32?view=net-6.0)

    Struct

    // Size = 4 because BitVector32 is 4 bytes
    [StructLayout(LayoutKind.Explicit, Size = 4, CharSet = CharSet.Ansi)]
    public struct Foo
    {
        public Foo() {
            // Creates and initializes a BitVector32.
            // 4 bytes
            // 00000000 00000000 00000000 00000000
            data = new BitVector32(0);
    
            bit1 = BitVector32.CreateMask();
            bit2 = BitVector32.CreateMask(bit1);
            bit3 = BitVector32.CreateMask(bit2);
            // ...
        }
    
        [FieldOffset(0)]
        public BitVector32 data;
    
        private static int bit1;
    
        private static int bit2;
    
        private static int bit3;
    
        public bool Bit1
        {
            get => data[bit1];
            set => data[bit1] = value;
        }
    
        public bool Bit2
        {
            get => data[bit2];
            set => data[bit2] = value;
        }
    
        public bool Bit3
        {
            get => data[bit3];
            set => data[bit3] = value;
        }
    
        public string ToHexString()
        {
            return data.Data.ToString("X");
        }
    }
    

    Program

    // -- Hex to struct
    // FFFFBBFF
    // 255      255      187      255
    // 11111111 11111111 10111011 11111111
    // var bytes = "FFFFBBFF".ToBytes();
    var bytes = { 255, 255, 187, 255 };
    
    var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
    var foo = (Foo)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(Foo));
    handle.Free();
    
    Console.WriteLine(foo.Bit1);
    Console.WriteLine(foo.Bit2);
    Console.WriteLine(foo.Bit3);
    // ...
    
    // -- Or struct to hex
    var foo = new Foo();
    foo.Bit1 = true;
    foo.Bit2 = false;
    foo.Bit3 = true;
    // ...
    
    Console.WriteLine(foo.ToHexString());
    

    I know it's not perfect, it works for me and I hope it will help others.

    Have a nice day!