Piero Costa Piero Costa - 1 year ago 69
C# Question

How to transform an hexadecimal value into a bit position [BitMapping] in C#?

My problem is:

I have an array, more precisely a

where the KEY INT is a hexadecimal value and the string is the meaning of that bit. Eg.:

Key, Value
1 Cat
2 Dog
4 Ant
80 Whale

I need to translate the hexadecimals values into the BIT POSITION. That is:

1 Cat
2 Dog
3 Ant
8 Whale

How can I do that in C# ?

Thank you all.

Answer Source

I'm not sure exactly what you're going for, but have you considered using an enum?

enum MyEnum
    Cat = 1,
    Dog = 2,
    Ant = 4,
    Whale = 8

If you have a hex string, convert it to an int, and then you can figure out which bits are on or off.

Convert to string:

string hexString = "80";
int hexInt = Convert.ToInt32(hexString, 16);

Check nth bit:

// Let's say you want to see if the 8th bit is on.
if (((1 << 7) & hexInt) > 0)
    // our 8th bit is on
    // our 8th bit is off

I would recommend making a method to check the nth bit like so:

public bool checkBit(int bitPosition, int value)
    // returns true if bit is on, else false
    return (((1 << bitPosition) & value) > 0);

Note that the first bit position is 0. So whatever bit position you want to check, subtract 1.

Again, still not exactly sure what you're going for, but if you want to get a hex value for nth bit. You could do something like this:

// remember that the first bit position will be 0.
public string getHexStringForBitPosition(int bitPosition)
     // we can't go higher than 64.
     if (bitPosition > 63)
         return "0";
     ulong myVal = 1 << bitPosition;
     return myVal.ToString("X");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download