Priya Kothari
Priya Kothari

Reputation: 13

bits and bytes in java

Can we have in Java one byte whose upper 4 bits represent values like 0x40/0x80 and lower 4 bits representing values like 0,1,2,3.If yes then how do we retrieve values out of that on byte?Any help is greatly appreciated.

Upvotes: 1

Views: 875

Answers (2)

George Sovetov
George Sovetov

Reputation: 5238

You can create wrapper class for byte or int with methods that fidget bits.

int first4bits = (byteContainer >> 4) & 0xF;
int last4bits = byteContainer & 0xF;

The problem is that such actions are inappropriate in Java.

Upvotes: 1

President James K. Polk
President James K. Polk

Reputation: 42009

A simple example is probably easier than using words to describe it.

byte data = 0x74;
int high4 = (data >> 4) & 0xf;
int low4 = data & 0xf;

Upvotes: 1

Related Questions