Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if bit is set in byte java

Tags:

android

I have a byte, and I have a function that checks whether the n-th bit index of the byte is a 1 or a 0. The function returns true if the bit is a 1 and false if the bit is a 0.

How I do, Thank.

like image 305
Thị Duyên Avatar asked Oct 20 '25 09:10

Thị Duyên


1 Answers

You need to and your value with a binary mask where the bit to test is set to 1:

boolean test(int value) {
     return (value & (1<<N)) != 0;
}

Here 1<<N constructs such a mask where bit N is set to 1, and the others are set to 0. Otherwise you can hand-craft your mask.

like image 93
ChrisJ Avatar answered Oct 21 '25 23:10

ChrisJ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!