简体   繁体   English

使用 C# 设置字节数组中的位

[英]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 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使用 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.您不能依赖 GetBytes 来获取负数,因为它可以补充位,而这不是您所需要的。

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.相反,您需要进行边界检查以确保数字是可表示的,然后对给定数字的绝对值使用 GetBytes。

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).该方法的参数是 'short' 所以我们 GetBytes 返回一个大小为 2 的字节数组(您不需要超过 16 位)。

The rest is in the comments below: rest 在下面的评论中:

        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
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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