2012-02-24 104 views
1

在C#10位,我将如何去设置2个字节,其中第一个10位代表一个十进制值和下一个6代表不同的十进制值?修改的2个字节

因此,如果第一个值是“8”(前10个比特)和第二“2”(剩余6个比特),我需要“0000001000 000010”结束了一个字节数组内。

谢谢! 广告

+1

那是10位还是10位? ;) – demoncodemonkey 2012-02-24 19:48:49

+0

@demoncodemonkey:你的意思是'字节或bits'? :) – sll 2012-02-24 19:50:54

+0

闻起来像功课给我。 – 2012-02-24 19:53:18

回答

4
UInt16 val1 = 8; 
UInt16 val2 = 2; 
UInt16 combined = (UInt16)((val1 << 6) | val2); 

如果你需要在一个字节数组,你可以传递结果到BitConverter.GetBytes method

byte[] array = BitConverter.GetBytes(combined); 
+0

'UINT16结合=(VAL1 << 6)| val2;'不编译,'不能将类型'int'隐式转换为'ushort'。一个显式转换存在(是否缺少强制转换?)' – sll 2012-02-24 19:54:34

+0

@sll只需添加一个演员和会的。 – 2012-02-24 20:04:47

+0

编辑为将Int32强制转换为UInt16。 – Justin 2012-02-24 20:07:07

1
int val1 = 8; 
int val2 = 2; 

// First byte contains all but the 2 least significant bits from the first value. 
byte byte1 = (byte)(val1 >> 2); 

// Second byte contains the 2 least significant bits from the first value, 
// shifted 6 bits left to become the 2 most significant bits of the byte, 
// followed by the (at most 6) bits of the second value. 
byte byte2 = (byte)((val1 & 4) << 6 | val2); 

byte[] bytes = new byte[] { byte1, byte2 }; 

// Just for verification. 
string s = 
    Convert.ToString(byte1, 2).PadLeft(8, '0') + " " + 
    Convert.ToString(byte2, 2).PadLeft(8, '0'); 
0

不占任何溢出:

private static byte[] amend(int a, int b) 
{ 
    // Combine the datum into a 16 bits integer 
    var c = (ushort) ((a << 6) | (b)); 
    // Fragment the Int to bytes 
    var ret = new byte[2]; 
    ret[0] = (byte) (c >> 8); 
    ret[1] = (byte) (c); 

    return ret; 
} 
0
ushort value = (8 << 6) | 2; 
byte[] bytes = BitConverter.GetBytes(value);