Question

If i take a uint value = 2921803 (0x2C954B), which is really a 4 byte package (4B 95 2C 00) and i want to get the 16 least significant bits of the byte version of it using bitarray, how would i go about it?

This is how i am trying to do it:

byte[] bytes = BitConverter.GetBytes(value);  //4B 95 2C 00  - bytes are moved around
BitArray bitArray = new BitArray(bytes); //entry [0] shows value for 1101 0010 (bits are reversed)

At this point, i am all turned around. I did try this:

byte[] bytes = BitConverter.GetBytes(value);

Array.Reverse(bytes);
BitArray bitArray = new BitArray(bytes);

Which gave me all the bits but completely reversed, reading from [31] to [0]. ultimately, i'm expecting/hoping to get 19349 (4B 95) as my answer.

This is how i was hoping to implement the function:

private uint GetValue(uint value, int bitsToGrab, int bitsToMoveOver)
{
    byte[] bytes = BitConverter.GetBytes(value);
    BitArray bitArray = new BitArray(bytes);

    uint outputMask = (uint)(1 << (bitsToGrab - 1));
    //now that i have all the bits, i can offset, and grab the ones i want
    for (int i = bitsToMoveOver; i < bitsToGrab; i++)
    {
        if ((Convert.ToByte(bitArray[i]) & 1) > 0)
        {
            outputVal |= outputMask;
        }

        outputMask >>= 1;
   }

}
Était-ce utile?

La solution

The 16 least significant bits of 0x2C954B are 0x954B. You can get that as follows:

int value = 0x2C954B;

int result = value & 0xFFFF;
// result == 0x954B

If you want 0x4B95 then you can get that as follows:

int result = ((value & 0xFF) << 8) | ((value >> 8) & 0xFF);
// result == 0x4B95

Try this:

uint value = 0x002C954Bu;

int reversed = Reverse((int)value);
// reversed == 0x4B952C00;

int result = Extract(reversed, 16, 16);
// result == 0x4B95

with

int Extract(int value, int offset, int length)
{
    return (value >> offset) & ((1 << length) - 1);
}

int Reverse(int value)
{
    return ((value >> 24) & 0xFF) | ((value >> 8) & 0xFF00) |
           ((value & 0xFF00) << 8) | ((value & 0xFF) << 24);
}

Autres conseils

unit - 32bits Basically you should set 16 most significant bits to zero, so use bitwise AND operator:

uint newValue = 0x0000FFFF & uintValue;
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top