[英]Split number into two parts
I'm trying to split number (8bit) (0..255) into two numbers like this: 100 (binary 01100100) into 6(0110) and 4(0100). 我正在尝试将数字(8bit)(0..255)分成两个数字,例如:100(二进制01100100)分为6(0110)和4(0100)。
In CI do it in such way: 在CI中,可以这样进行:
short row = value >> 4; //value - uint8_t
short col = (row << 4) ^ value;
In Java I do it the other way (because C like code don't work properly): 在Java中,我采用另一种方式(因为类似C的代码无法正常工作):
short v1 = (byte)(value >> 4);
short v2 = (byte)((byte)(value << 4) >>> 4);
It works for numbers from 0 to 103. But for numbers greater than 103 it doesn't work. 它适用于从0到103的数字。但是对于大于103的数字则不起作用。
ps Actually problem is here: ps实际问题在这里:
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;
Fix. 固定。
I fixed it in such way: 我以这种方式修复它:
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);
But I prefer the C way, it's more simple. 但是我更喜欢C方式,它更简单。
short row = (value >> 4) & 0x0F;
short col = value & 0x0F;
This should also work in C. 这在C语言中也应该起作用。
& keeps only the bits which are 1 at the same position: &仅将1的位保留在同一位置:
11111000 // 104
00001111 // 0x0F == 15
--------
00001000 // 104 & 0x0F == 8
// because only the fourth bit from right is 1 in both numbers!
unsigned char f = 100;
unsigned char first = f >> 4;
unsigned char second = 0xF & f;
printf("%d %d", first, second);
00001111 if you bitwise and with number you will get last 4 bit 00001111如果按位并带有数字,您将获得最后4位
Try this. 尝试这个。
short v1 = (byte)(value >> 4);
short v2 = (byte)((byte)(value << 4) >>> 4);
if(v2<0){
v2 = (short) -v2;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.