Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the value of a bit at a certain position from a byte?

Tags:

java

byte

bit

If I have a byte, how would the method look to retrieve a bit at a certain position?

Here is what I have know, and I don't think it works.

public byte getBit(int position) {     return (byte) (ID >> (position - 1)); } 

where ID is the name of the byte I am retrieving information from.

like image 211
Glen654 Avatar asked Feb 20 '12 00:02

Glen654


People also ask

How do I access a specific bit?

For accessing a specific bit, you can use Shift Operators . If it is always a 1 that you are going to reset, then you could use an & operation. But, if it can also take 0 value, then & operation will fail as 0 & 1 = 0 . You could use | (OR) during that time.

How do you read bits in a byte?

You can mask out the bits you want from a byte using bitwise AND. In general, to test for individual bits, C has bitwise operators. Example: SO: C/C++ check if one bit is set in, i.e. int variable.

How do I get bits in Java?

Use Long. toString with the radix: String bits = Long. toString(someLong, 2);


1 Answers

public byte getBit(int position) {    return (ID >> position) & 1; } 

Right shifting ID by position will make bit #position be in the furthest spot to the right in the number. Combining that with the bitwise AND & with 1 will tell you if the bit is set.

position = 2 ID = 5 = 0000 0101 (in binary) ID >> position = 0000 0001  0000 0001 & 0000 0001( 1 in binary ) = 1, because the furthest right bit is set. 
like image 109
Hunter McMillen Avatar answered Sep 24 '22 02:09

Hunter McMillen