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
.
Unfortunately bytes in Java are signed. All you can do is try a larger data type or a custom class.
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.
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.
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.
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};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With