Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: have integer, need it in byte in 0x00 format

Tags:

java

I have an integer used to seed my for loop:

for(int i = 0; i < value; i++)

Within my for loop I am seeding a byte array with byte content values that increment +1. For instance new byte[]{0x00}; But the 0x00 needs to be 0x01 on the next iteration, how can I convert my value of integer i into a value of byte in the 0x00 format?

I tried things like Byte.valueOf(Integer.toHexString(i)) but this just gives me a value that looks like 0 instead of 0x00.

like image 363
CQM Avatar asked Oct 15 '11 23:10

CQM


People also ask

Can we assign int to byte in Java?

Unfortunately bytes in Java are signed. All you can do is try a larger data type or a custom class.

Can we store integer in byte?

1 Integers. Integers are commonly stored using a word of memory, which is 4 bytes or 32 bits, so integers from 0 up to 4,294,967,295 (232 - 1) can be stored.

Should I use byte instead of int?

Looking at the benchmark results in @meriton's answer, it appears that using short and byte instead of int incurs a performance penalty for multiplication. Indeed, if you consider the operations in isolation, the penalty is significant.

Should I use byte or int in Java?

int datatype is the most preferred type for numeric values. long datatype is less frequently used. It should only be used when the range of the numeric value is too high. It requires the most memory(8 bytes) in comparison to the other three data-types.


1 Answers

new byte[]{0x00}

is actually equivalent to

new byte[]{0}

The 0x00 notation is just an alternative way to write integer constants, and if the integer constant is in the range -128 to 127, then it can be used as a byte.

If you have an existing integer variable that you want to use, and its value is in the range -128 to 127, then you just have to cast it:

int i = 1;
new byte[]{(byte)i};
like image 135
ruakh Avatar answered Nov 04 '22 01:11

ruakh