Reputation: 174
I'm trying to split number (8bit) (0..255) into two numbers like this: 100 (binary 01100100) into 6(0110) and 4(0100).
In C I do it in such way:
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):
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.
p.s. Actually problem is here:
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.
Upvotes: 0
Views: 916
Reputation: 6724
Try this.
short v1 = (byte)(value >> 4);
short v2 = (byte)((byte)(value << 4) >>> 4);
if(v2<0){
v2 = (short) -v2;
}
Upvotes: 0
Reputation:
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
Upvotes: 1
Reputation: 7994
short row = (value >> 4) & 0x0F;
short col = value & 0x0F;
This should also work in C.
& keeps only the bits which are 1 at the same position:
11111000 // 104
00001111 // 0x0F == 15
--------
00001000 // 104 & 0x0F == 8
// because only the fourth bit from right is 1 in both numbers!
Upvotes: 2