Reputation: 838
I have a binary number that looks like this:
00000000 00000000 00000011 00001101 = 781 integer value = integer name "packed"
How am i able to extract each of those as separate integer values using bit wise in java. Like the following:
int a = (function) = 00000000;
int b = (function) = 00000000;
int c = (function) = 00000011;
int d = (function) = 00001101;
If you can see what i am doing up there.. I want the first 8 into one integer the next into a second integer and so on.. I think you do this using bit wise in java but i am completely unsure. Any help is appreciated. Sorry but i am completely new to this kind of thing and really need help with this, Thanks! Basically (function) should equal something like this:
packed >> 5; (I know this isn't nearly right that is why i am needing help on this)...
Thanks!
Upvotes: 1
Views: 2194
Reputation: 178253
You are right in that bitwise operations are needed here.
First, use a mask to isolate only the bits you're interested in, turning all other bits off:
value & 0xFF000000 // isolate most significant 8 bits
value & 0x00FF0000 // isolate next 8 bits
value & 0x0000FF00 // isolate next 8 bits
value & 0x000000FF // isolate least significant 8 bits
Then shift the bits into the least significant bits to store into a
, b
, c
, and d
(an unsigned bitshift):
(value & 0xFF000000) >>> 24 // Shift bits 24-31 to bits 0-7
(value & 0x00FF0000) >>> 16 // Shift bits 16-23 to bits 0-7
(value & 0x0000FF00) >>> 8 // Shift bits 8-15 to bits 0-7
(value & 0x000000FF) // No need to shift the last one!
Upvotes: 5
Reputation: 1284
This can be achieved by performing a bitwise-AND operation using a mask, followed by bit-shift. The mask is simply a number in which all bits that you are not interested in are set to zero. It masks the bits you do not care about.
int BYTE_ONE_MASK = 0xFF;
int BYTE_TWO_MASK = 0xFF00;
int BYTE_THREE_MASK = 0xFF0000;
int BYTE_FOUR_MASK = 0xFF000000;
The bit-shift is necessary for all bytes other than the least significant one:
int a = (val & BYTE_ONE_MASK);
int b = (val & BYTE_TWO_MASK) >> 8;
int c = (val & BYTE_THREE_MASK) >> 16;
int d = (val & BYTE_FOUR_MASK) >> 24;
This can be generalised into a function such as the following:
// Assuming the first byte is n = 0.
public static int getByte(int val, int n) {
int shift = n * 8;
int mask = 0xFF << shift;
return (val & mask) >> shift;
}
Upvotes: 4
Reputation: 59273
Try something like this:
public byte getNthByte(int n, int packed) {
// shift the desired bits into the last 8 bits
int shifted = packed >> (8 * n);
// and now get those bits
int masked = 0x000000FF & shifted;
return masked;
}
Then
int a = getNthByte(3);
int b = getNthByte(2);
int c = getNthByte(1);
int d = getNthByte(0);
Upvotes: 3