int - How to display a hex/byte value in Java -


int myint = 144; byte mybyte = /* byte conversion of myint */; 

output should mybyte : 90 (hex value of 144).

so, did:

byte mybyte = (byte)myint; 

i got output of mybyte : ffffff90. :(

how can rid of ffffffs?

byte signed type. values in range -128 127; 144 not in range. there no unsigned byte type in java.

if using java 8, way treat value in range 0 255 use byte.tounsignedint:

string output = string.format("%x", byte.tounsignedint(mybyte)); 

(i don't know how formatted integer hex output. doesn't matter.)

pre-java 8, easiest way is

int bytevalue = (int)mybyte & 0xff; string output = string.format("%x", bytevalue); 

but before either of those, make sure want use byte. chances don't need to. , if want represent value 144, shouldn't use byte, if don't need to. use int.


Popular posts from this blog