我試圖將數字(8位)(0..255)拆分爲兩個數字,如: 100(二進制01100100)分成6(0110)和4(0100)。拆分爲兩部分
在CI做到在這樣的方式:
short row = value >> 4; //value - uint8_t
short col = (row << 4)^value;
在Java中我做的其他方式(因爲C代碼一樣無法正常工作):
short v1 = (byte)(value >> 4);
short v2 = (byte)((byte)(value << 4) >>> 4);
它適用於數字從0到103.但對於大於103的數字,它不起作用。
p.s. 其實問題在這裏:
short v2 = (byte)((byte)(value) >>> 4);
=>104 (1101000). I expected to see something like this: 00001000, but result is 11111000
=>103 (1100111). Result is 111;
修復。
我固定它以這樣的方式:
short value = (byte)255;
short v1 = 0;
short v2 = 0;
for(int i = 3; i >= 0; i--) {
v2 = (short) (v2 << 1 | ((value >> i) & 1));
v1 = (short) (v1 << 1 | (value >> (i + 4) & 1));
}
System.out.println(v1 + " " + v2);
但我更喜歡的C方式,它更簡單。
在Java中沒有無符號數字。 –
你的意思是說我不能以這種方式拆分數字嗎?我應該用另一種方法嗎? – FruitDealer
您的解決方案非常複雜,即使您的C解決方案對於簡單任務來說也非常複雜。 –