2012-02-24 53 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);