when is it needed to cast hex literals in java to (byte)? - java

For testing purposes, I tried to create an array like this:
byte[] expected = new byte[]{0x2f, 0x0d4, 0xe1, 0xc6, 0x7a, 0x2d, 0x28, 0xfc}
I expected, that java will complain and will ask me to cast every literal here to (byte), but unexpectedly, it asked me only to convert 0x4d, for example, but not 0x2f. The working example:
new byte[]{0x2f, (byte) 0xd4, (byte) 0xe1, (byte) 0xc6, 0x7a, 0x2d, 0x28, (byte) 0xfc}
How does that work?

I suspect it is because the Java byte is signed, thus you have a range between -128 and 127. So all values >127 (0x80) have to be explicitly converted.

An number literal without a l, d or f is an int value, so values 0x80 and larger have to be cast. One way to cover lots of hex values is to use the following
byte[] bytes = new BigInteger("2fd4e1c67a2d28fc", 16).toByteArray();
System.out.println(Arrays.toString(bytes));
prints
[47, -44, -31, -58, 122, 45, 40, -4]
This avoids some of the tedious , (byte) 0x between values.

Integer literal between -128 to 127 will be automatically converted into target type and Java has signed types only.

Related

Convert hex code in string to hex code in byte (java)

I have a hex code in string
example
String a="0x52";
I want to store this hex value in a byte
example
byte b=(do something with a so i can store it in b);
so byte b is going to store 0x52
How to achieve this ?
Just for reference my teacher gave this sample code
public byte[] CONSIGNMENT_0 = { 0x52, 0x44, 0x54, 0x30, 0x31, 0x9, 0x6f, 0x6e,
0x65, 0xa, 0x32, 0x9, 0x74, 0x77, 0xa, 0xd };
And its working perfectly so we can store 0x52 in a byte variable.
You are writing a hex constant, so you can parse it with Integer.parseInt(String, int) (the second argument is a base) and then cast it to a byte. Like,
String a = "0x52";
byte b1 = 0x52;
byte b2 = (byte) Integer.parseInt(a.substring(2), 16);
System.out.println(b1 == b2);
Outputs
true

Hardcode string on a javacard

I need to save a variable on a JavaCard. Javacard's don't support Strings, so I have to hardcode some String variables as byte arrays.
Unfortunately, I don't know how to achieve this format:
new byte[]{0x4A, 0x61, 0x6E, 0x20, 0x56, 0x6F, 0x73, 0x73, 0x61, 0x65, 0x72, 0x74};
Is there an online tool available? Or is there a program that output's it that way so I can copy paste the output and use that for hardcoding?
You don't need any tool for that. If you want to store an string in your applet in the applet developing step (I mean in the programming phase) use a byte array as below :
public static byte[] myFiled = {(byte)'T', (byte)'E', (byte)'S', (byte)'T'};
or use Hex values instead of the letters:
public static byte[] myFiled = {(byte)0x10, (byte)0x11, (byte)0x12, (byte)0x13};
It's necessary to cast the array elements to byte explicitly
And if you want to store the string after developing in installing your applet, first convert it to its hex value using this online tool for example, and then send it to card in the data field of an APDU command. And then using arrayCopy or arrayCopyNonAtomic methods store it in you byte array.
Just use String::getBytes():
String a = "HelloWorld";
byte[] inBytes = a.getBytes();
System.out.println(Arrays.toString(inBytes));
OUTPUT:
[72, 101, 108, 108, 111, 87, 111, 114, 108, 100]
IDEONE DEMO
ADD ON: as #AndyTurner mentioned, you can specify charset using String::getBytes(Charset).
Find here a nice explanation.
Here's a method to convert a string to an array literal that represents US-ASCII–encoded bytes.
static String format(String str)
{
byte[] encoded = str.getBytes(StandardCharsets.US_ASCII);
return IntStream.range(0, encoded.length)
.mapToObj(idx -> String.format("0x%02X", encoded[idx]))
.collect(Collectors.joining(", ", "{ ", " }"));
}
Because it uses ASCII, the high bit of each byte is zero, and no downcasts to byte are required.

Declare byte[] in java?

i try :
byte[] Data = { 0xA3, 0x34, 0x33, 0x33, 0x00};
but at "0xA3" it said "required byte found int",so what's problem here ?
0xA3 is 163 which is out of bounds for byte which I think can be -128 -> +127.
You can find more details here
at "0xA3" it said "required byte found int", so what's problem here
The problem is that the range of a byte in Java is -128..127.
The solution is that you need to write a (byte) cast in front of 0xA3.

How to create a Java Hexadecimal Array

This does not seem to be appropriate. Is there a way to create a hexadecimal array?
float[] bitBytes = {0x80, 0x40, 0x20, 0x10, 8, 4, 2, 1};
for (int k = 0; k < alot; k++) {
BitSet.set(increment++, ((array[k] & (bitBytes[k%8]& 0xff)) != 0));
}
Hexadecimals is a representation of bytes as a String, or at least an array of characters. It is mainly used for human consumption, as it is easier to see the bit value of the bytes.
To create a byte array containing byte values, you can use the following construct:
final byte[] anArray = { (byte) 0x10, (byte) 0x80 };
The cast to byte - (byte) - is really only required for values of 0x80 or over as bytes are signed in Java and therefore only have values ranging from -0x80 to 0x7F. Normally we only deal with unsigned values though, so we need the cast.
Alternatively, for larger strings, it can be useful to simply supply a hexadecimal string to a decoder. Unfortunately the idiots that have thought out the standard API still haven't defined a standard hexadecimal codec somewhere in java.lang or java.util.
So you can use another library, such as the Apache codec library or a self written function. Stackoverflow to the rescue.
Convert a string representation of a hex dump to a byte array using Java?
If you want to have a BitSet of the values in the byte array, please use BitSet.valueOf(byte[])
byte[] biteBytes = new byte[8];
for (int j = 0; j < bitBytes.length; j++) {
bitBytes[j] = (byte) (Math.pow(2,j));
}

Insert byte into a byte array

I really can't believe I'm asking this but everything I read is either converting from int to byte to string to byte or something. I am literally trying to insert a byte into a byte array. Or for that matter, initialize a byte array with bytes, not ints.
byte[] header = {0x8b, 0x1f, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03};
The compiler complains that they are ints. I'm trying to insert bytes.
byte is a signed integer in the range [-128,127]. 0x8b is 139d, so you'll need to cast it to a byte (byte)0x8b or use a value in the proper range such as -0x75 (the equivalent of casting 0x8b to byte).
The compiler threats literals like 0x8b as integers, so you have to explicitly cast to byte
byte[] header = { (byte) 0x0b, (byte) 0x1f };
Bytes are signed integers, so cannot exceed 127. 0x8b is therefore too big.
Reference
public static byte[] bytes(byte... bytes){ return bytes; }
byte[] header=bytes(0x8b, 0x1f, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03);

Categories