I have a byte array i.e from byte[0] to byte[2]. I want to first split byte[0] into 8 bits. Then bytes[1] and finally bytes[2]. By splitting I mean that if byte[0]=12345678 then i want to split as variable A=8,Variable B=7, variable C=6,Variable D=5,........ Variable H=0. How to split the byte and store the bits into variables? I want to do this in JAVA
2 Answers
well the bitwise operations seem to be almost what you're talking about. a byte is composed of 8 bits, and so it goes in the rage of 0 to 255. written in binary that's 00000000 to 11111111.
Bitwise operations are those that basically use masks to get out as much info as possible out of a byte.
Say for instance you have your 1101 0011 byte (space added for visibility only) = 211 (decimal). You can split that into 2 "variables" b1 and b2 of half a byte each. they'll thus cover the range of 0 to 15.
How you do this is by defining some masks. A mask to get your first half-a-byte-value would be 0000 1111. You take your value of 11010011 apply the bitwise and (& ) operator to it. So saying byte b = 211; byte mask1=15; OR byte b=0x11010011; byte mask1=0x00001111; you then have your variable byte b1=b & mask1;
Thus applying that operation would result in b1=00000011 = 3; With a mask byte mask2=0x11110000; applying the same operation on b, you'd get byte b2=mask2 & b = 0x11010000;
Now of course that leaves the number b2 possibly too large for you. All you have to do if you want to grab the value 0x1101 is to right shift it. Thus b2>>=4;
You can have your masks in any form, but it's usual to have them in decimal as the powers of 2 (so that you can take any bit out of your byte) or decide what range you want on your variables and make the mask "larger" like 0x00000011, or ox00001100. Those 2 masks would respectively get you 2 values from a byte, each value ranging from 0 to 3, values that you can fit 4 inside a byte.
for more info, chek out the relevant wiki.
Sorry, the values were a little off (since byte seems to go from -128 to 127, but the idea is the same.
Second edit (never used bitwise operations myself lol)... the "0x" notation is for hexadecimals. So you'll actually have to calculate for yourself what 01001111 actually means... pretty sucky :| but it's gonna do the trick.
Comments
boolean a = (theByte & 0x1) != 0; boolean b = (theByte & 0x2) != 0; boolean c = (theByte & 0x4) != 0; boolean d = (theByte & 0x8) != 0; boolean e = (theByte & 0x10) != 0; boolean f = (theByte & 0x20) != 0; boolean g = (theByte & 0x40) != 0; boolean h = (theByte & 0x80) != 0; 3 Comments
!= 0. I was in a bit of a hurry, I guess.
Integer.toBinaryString(your_byte_value)?12345678value, by sun specification a byte is-128to127.