Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Byte arrays in java

Tags:

java

hex

byte

Hey I need to store the following hex value in a byte array - 0xCAFEBABEDEADBEEF.

So I tried to store it like so.

byte[] v0 = {11001010,11111110,10111010,10111110,11011110,10101101,10111110,11101111};

where 11001010 is CA in binary, 11111110 is FE in binary etc.

But I get an error saying 11001010 is an int, so I presume this is because bytes are signed bytes in java, and we can only have values between +127 and -128.

So is there way I can do this in java(maybe using unsigned bytes...if they exist!?) Thanks guys.

like image 243
user1974753 Avatar asked Dec 01 '22 20:12

user1974753


1 Answers

Put 0b in front of the number. You may also have to cast to byte:

byte[] v0 = {(byte)0b11001010,(byte)0b11111110,...};

The 0b prefix means it is a binary number.

If you want it to be easier to read, you can use 0x for hexadecimal:

byte[] v0 = {(byte)0xCA,(byte)0xFE,(byte)0xBA,(byte)0xBE,...};

Here's a way to do it (binary form) if you're using a Java version less than 7:

byte[] v0 = {Byte.parseByte("11001010", 2),...);
like image 182
tckmn Avatar answered Dec 04 '22 09:12

tckmn