Byte arrays in java

Hi, I need to store the next hexadecimal value in a byte array - 0xCAFEBABEDEADBEEF.

So, I tried to save it like that.

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

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

But I get the error 11001010 - this is int, so I assume that this is because bytes are bytes in java, and we can only have values ​​between +127 and -128.

So, I can do it in java (possibly using unsigned bytes ... if they exist !?) Thanks guys.

+4
source share
3 answers

Put 0b in front of the number. You may also need to click byte :

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

The prefix 0b means that it is a binary number.

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

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

Here is a way to do this (binary form) if you are using a Java version less than 7:

 byte[] v0 = {Byte.parseByte("11001010", 2),...); 
+9
source

The literal 11001010 represents a decimal of the int type and the values 11,001,010 are 11 million and something.

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

However, note that the type of the even binary (or hexadecimal) literal is still int . This, together with the fact that bytes (unfortunately) are signed in Java (thus their value is in the range -128 to 127 ), leads to the fact that a literal with a value greater than 127 must manually 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 a byte will be -111 (145 - 256). To return an 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 

See this question for more details.

+5
source

If you are writing bytes, you can use:

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

or

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

All Articles