Java Bit-Level Programming
Hi,
I am working on a file which has these chracteristics.
File has many frames and each frame has certain no of bytes.
a) One byte of a file is defined as
frame_type (4 bits) Value = 0100b
error_detection_type (2 bits)Value = 00b
SOF (1 bit)Value = 1b
EOF (1 bit)Value = 0b
I can read bytes of a file in an array, but how to read bit within the byte.
Ex: After reading the bytes in a array how do to verify the bit inside the byte (say EOF=0b or SOF=1b).
# 3
> Hi,> > for some typical operations You can use Integer, ...No, that will just return a String representation of an integer value which is not suitable for bitwise operations.@OP: better look at the link posted in reply #1.
# 5
> 2prometheuzz
>
> As I can see there is no need to change something
> only to read. So, Your comment looks unrelevant.
>
> Regards.
In the original post the OP mentioned that a file consist of many frames and each frame consists of several bytes.
So, you suggest converting each byte to a binary String representation and then checking that String if a certain bit is present in some position? That would mean using an awfull lot of charAt(...) or substring(...) methods on a lot of String objects: not very efficient...
@OP: better use bitwise and bit shift operators.
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/op3.html
# 8
> ....
> (is there any other way to read the bit value
> ex; 3rd bit within the byte. )
> ...
Yes: as already mentioned in the first reply: by using some simple bit shifting operations!
Example:
byte theByte = 92;
// shift all bits two places to the right (>> operator), and AND (& operator) the result with the number 1
int _3rdBit = (theByte >> 2) & 1;
System.out.println("The third bit of "+theByte+" ("+
Integer.toBinaryString(theByte)+" in binary) = "+_3rdBit);
# 9
// 2 ^ 0 -> 1st Bit, 2 ^ 1 -> 2nd Bit, 2 ^ 2 -> 3rd Bitint _3rdBit = theByte & 4;Of course, _3rdBit here would be 4 not 1 if set.