4
votes

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.

3
It depends on what version of Java you are using. For 1.7, you can prefix each binary value with "0b", otherwise you will have to use hex and prefix each hex value with "0x".Kevin Mangold

3 Answers

10
votes

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),...);
5
votes

The literal 11001010 represents a decimal of int type and of value 11,001,010 - that is 11 milions and something.

If you're using Java 7, you can define binary literals using the 0b prefix, such as 0b11001010. To improve readability, you can put underscores in the values, such as 0b_1100_1010.

However, note that the type of even such binary (or hexadecimal) literal is still int. This, together with the fact that bytes are (unfortunately) signed in Java (thus their value is in range -128 to 127) results in the problem that a literal with a value larger than 127 has to be manually cast to byte:

// 0b_1001_0001 or 0x91 is 145 in decimal
byte b1 = (byte) 0b_1001_0001;
byte b2 = (byte) 0x91;

However, the value of such byte will be -111 (145 - 256). To get back the unsigned value, you need to manually add the module (256) to the value:

int i1 = b1 + 256;
int i2 = b1 & 0xff;
// both i1 and i2 are 145

For more information see this question

3
votes

If write byte to byte, you can use:

byte[] v0 = {0b11001010, 0b11111110, 0b10111010, ... }

or

byte[] v0 = {0xCA, 0xFE, ... }