简体   繁体   中英

Setting bits in a byte array with C#

I have a requirement to encode a byte array from an short integer value The encoding rules are The bits representing the integer are bits 0 - 13 bit 14 is set if the number is negative bit 15 is always 1. I know I can get the integer into a byte array using BitConverter

byte[] roll = BitConverter.GetBytes(x);

But I cant find how to meet my requirement Anyone know how to do this?

You should use Bitwise Operators .

Solution is something like this:

 Int16 x = 7;

 if(x < 0)
 {
        Int16 mask14 = 16384; // 0b0100000000000000;
        x = (Int16)(x | mask14);
 }
 Int16 mask15 = -32768; // 0b1000000000000000;
 x = (Int16)(x | mask15);
 byte[] roll = BitConverter.GetBytes(x);

You cannot rely on GetBytes for negative numbers since it complements the bits and that is not what you need.

Instead you need to do bounds checking to make sure the number is representable, then use GetBytes on the absolute value of the given number.

The method's parameter is 'short' so we GetBytes returns a byte array with the size of 2 (you don't need more than 16 bits).

The rest is in the comments below:

        static readonly int MAX_UNSIGNED_14_BIT = 16383;// 2^14-1

        public static byte[] EncodeSigned14Bit(short x)
        {
            var absoluteX = Math.Abs(x);
            if (absoluteX > MAX_UNSIGNED_14_BIT) throw new ArgumentException($"{nameof(x)} is too large and cannot be represented");

            byte[] roll = BitConverter.GetBytes(absoluteX);

            if (x < 0)
            {
                roll[1] |= 0b01000000; //x is negative, set 14th bit 
            }

            roll[1] |= 0b10000000; // 15th bit is always set

            return roll;
        }
        static void Main(string[] args)
        {
            // testing some values
            var r1 = EncodeSigned14Bit(16383); // r1[0] = 255, r1[1] = 191
            var r2 = EncodeSigned14Bit(-16383); // r2[0] = 255, r2[1] = 255
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM