c# - 我应该如何从位创建字节?

时间:2017-02-21 13:41:51

标签: c# bit-manipulation

我正在开发将通过RTP发送数据的应用,但我几乎从不使用字节。现在我正在尝试使用BitArray

byte[] toSend = new byte[12];
BitArray b = new BitArray(new int[] { 2 });
b.CopyTo(toSend, 0);

但它适用于Int32,因此2表示为0100..0,这不是我需要的。我在这里有两个问题:

  1. 如何将2|1|1|4位组合成一个字节?我认为应该有类似的东西:

    int version = 2;//2 bits
    int padding = 0;//1 bit
    int extension = 0;//1 bit
    int ccrc = 0;//4 bits
    
    byte[] toSend = new byte[1]{version+padding+extension+ccrc};
    
  2. 对于某些标题,保留了16位,所以我需要一些东西 像这样:0000000000000000(16),但我不知道如何创建这种变量,以及如何将16位写入两个字节。

2 个答案:

答案 0 :(得分:2)

如果我理解正确,你试图从位创建一个字节。

为什么不使用一个带有字节的函数,位值和位置来放置位here

答案 1 :(得分:2)

从第二点开始。如何创建一个包含仅包含0的16位(2字节)的变量:

char _16bitsOfZero = '\0'; // this will have the default value of NULL character
// which basically is 0000 0000 0000 0000 

进一步从4个整数中创建一个字节值:

int version = 2; // 2 bits which will be shifted to the most left
int padding = 0; // 1 bit which will be shifted to the most left but just before version
int extension = 0; // 1 bit which will be shifted to right before padding
int ccrc = 0; // 4 bits that ... wont be shifted.

// first of all this all is going to be one byte ( 8 bits )
// 00 0 0 0000 <- beginning value
byte b = 0;
// now we want to shift our ccrc to be in the back
// 00 0 0 ccrc <- like this
// to put this value there we need to shift this 
b = (byte)ccrc;
// now we want to shift extension right after ccrc value
// remembering that ccrc is 4 bits wide :
b |= (extension << 4);
// now do the same with padding :
b |= (padding << 5); // 4 because previous value was 1 bit wide
// now the same with version :
b |= (version << 6);
// output from this should be :
// 10 0 0 0000
// which is 128

要检查128是否真的here

// to be more precise :
// assume ccrc = 15 ( 0000 1111 )
// and b = 0 ( 0000 0000 )
// now use shift :
b |=
    (ccrc << 1) // will produce the output of ( 0001 1110 )