Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find most significant bit (MSB)

I want to know which value the first bit of a byte has.

For example:

I have byte m = (byte) 0x8C;

How could I know if the first bit is an 1 or a 0 ?

Can anyone help me out ?

like image 958
João Nunes Avatar asked Nov 27 '22 07:11

João Nunes


1 Answers

It depends what you mean by "first bit". If you mean "most significant bit" you can use:

// 0 or 1
int msb = (m & 0xff) >> 7;

Or if you don't mind the values being 0x80 or 0, just use:

// 0 or 0x80
int msb = m & 0x80;

Or in fact, as a boolean:

// Uses the fact that byte is signed using 2s complement
// True or false
boolean msb = m < 0;

If you mean the least significant bit, you can just use:

// 0 or 1
int lsb = m & 1;
like image 98
Jon Skeet Avatar answered Dec 04 '22 22:12

Jon Skeet