Convert int to hex byte value - java

I want to read block wise data of NFC tag. For which the command is a byte array and it needs block number.
public static byte[] readSingleBlockCmd(int blockNo) {
byte[] cmd = new byte[3];
cmd[0] = (byte) 0x02;//flag
cmd[1] = (byte) 0x23;//cmd
cmd[2]= (byte)blockNo;
return cmd;
}
How can I change the int blockNo to its hexadecimal value , which can be cast to byte .I want the byte value and not an byte []
I have gone through the following links
Convert integer into byte array (Java)
How to autoconvert hexcode to use it as byte[] in Java?
Java integer to byte array
Thanks!

Converting an integer (in decimal) to hex can be done with the following line:
String hex = Integer.toHexString(blockNo);
Then to convert it to byte, you can use
Byte.parseByte(hex,16);
But if all you wanted to do is convert the parameter to bytes:
Byte.parseByte(blockNo);
would work too I guess. Correct me if I'm wrong.

Related

Store int 0-65535 on fixed 16-bit & convert back

I have int numbers with values between 0-65535. I need to store each number as a byte array of 2 bytes length, whether the number could fit on 1 byte as well or not. Once the numbers are stored in byte arrays, I need to be able to convert them back to int. Right now I don't know how to store a number that is not between -32,768 and 32,767 on 2 bytes and be able to properly convert it back to its original int value.
You can store values from 0-65535 in a char-value and convert a char to byte[] (with a length of 2) using the following method:
public static byte[] toBytes(char c) {
return ByteBuffer.allocate(Character.BYTES).putChar(c).array();
}
See here
EDIT:
Works backwards using ByteBuffer to:
public static char charFromBytes(byte[] bytes) {
return ByteBuffer.wrap(bytes).getChar();
}
Storing the first byte as: (byte) (myIntNumber >> 8) and the second as (byte) myIntNumber seems working just fine for int -> byte array conversion, I'm still curious about how do I get back the int properly from a byte array.

Converting String to byte array for hex values

I am using a Android Phone to communicate with a BLE device.
The method to send data for the library needs byte[],
sharing one of the static example snippet:
public static final byte dataRequest[] = { 0x23, 0x57, 0x09, 0x03, (byte) 0xD4};
sendDataToDevice(dataRequest);
The data i am receiving from the user is in String, for example
String str1 = "D4";
now my question is , how to convert this String value (which is actually a hex value in String datatype) to byte, so that i can store these dynamic String values and convert and then insert it into byte[] like ,
byte[0] = convertToByte(str1);
where byte[0] must store value as 0xD9 or like the format given in static example.
You should just be able to use Integer#parseInt with a radix of 16 (hexadecimal) to convert a String to an int (which you can then cast to a byte and store in your array):
String str1 = "D4";
byte b = (byte) Integer.parseInt(str1, 16);
System.out.println(b);
Output:
-44
Note: Byte#parseByte can't be used in your example, as Byte#parseByte uses Integer#parseInt internally and parses D4 as 212, which is not a valid value for a signed byte.

char[] into ascii and decimal value (double) java

based on this array :
final char[] charValue = { 'u', ' ', '}','+' };
i want to print the double value and the ascii value from it in Java.
i can't find a proper solution for that in internet. I just found how to convert a single Character into Integer value. But what about many characters?
the main problem is, i have a large char[] and some double and int values are stored in. for double values they are stored within 4 bytes size and integer 1 or 2 bytes so i have to read all this and convert into double or integer.
Thanks for you help
When java was designed, there was C char being used for binary bytes and text.
Java made a clear separation between binary data (byte[], InputStream/OutputStream) and Unicode text (char, String, Reader/Writer). Hence Java has full Unicode support. The binary data, byte[], need information: their used encoding, in order to be convertable to text: char[]/String.
In Java a char[] will rarely be used (as in C/C++), and it seems byte[] is intended, as you mention 4 elements to be used for an int etcetera. A char is 16 bits, containing UTF-16 text.
For this case one can use a ByteBuffer either wrapping a byte[] or being taken from a memory mapped file.
Writing
ByteBuffer buf = ByteBuffer.allocate(13); // 13 bytes
buf.order(ByteOrder.LITTLE_ENDIAN); // Intel order
buf.putInt(42); // at 0
buf.putDouble(Math.PI); // at 4
buf.put((byte) '0'); // at 12
buf.putDouble(4, 3.0); // at 4 overwrite PI
byte[] bytes = buf.array();
Reading
ByteBuffer buf = ByteBuffer.wrap(bytes);
buf.order(ByteOrder.LITTLE_ENDIAN); // Intel order
int a = buf.getInt();
double b = buf.getDouble();
byte c = buf.get();

Java: Conversion of String to byte array, then to long value and vice versa

Basically, I'm looking for .NET's BitConverter.
I need to get bytes from String, then parse them to long value and store it. After that, read long value, parse to byte array and create original String. How can I achieve this in Java?
Edit: Someone did already ask similar question. I am looking more like for samples then javadoc reference ...
String has a getBytes method. You could use this to get a byte array.
To store the byte-array as longs, I suggest you wrap the byte-array in a ByteBuffer and use the asLongBuffer method.
To get the String back from an array of bytes, you could use the String(byte[] bytes) constructor.
String input = "hello long world";
byte[] bytes = input.getBytes();
LongBuffer tmpBuf = ByteBuffer.wrap(bytes).asLongBuffer();
long[] lArr = new long[tmpBuf.remaining()];
for (int i = 0; i < lArr.length; i++)
lArr[i] = tmpBuf.get();
System.out.println(input);
System.out.println(Arrays.toString(lArr));
// store longs...
// ...load longs
long[] longs = { 7522537965568945263L, 7955362964116237412L };
byte[] inputBytes = new byte[longs.length * 8];
ByteBuffer bbuf = ByteBuffer.wrap(inputBytes);
for (long l : longs)
bbuf.putLong(l);
System.out.println(new String(inputBytes));
Note that you probably want to store an extra integer telling how many bytes the long-array actually stores, since the number of bytes may not be a multiple of 8.

Convert INT(0-255) to UTF8 char in Java

since I need to control some devices, I need to send some bytes to them. I'm creating those bytes by putting some int values together (and operator), creating a byte and finally attaching it to a String to send it over the radio function to the robot.
Unfortuantely Java has some major issues doing that (unsigned int problem)
Does anybody know, how I can convert an integer e.g.
x = 223;
to an 8-bit character in Java to attach it to a String ?
char = (char)x; // does not work !! 16 bit !! I need 8 bit !
A char is 16-bit in Java. Use a byte if you need an 8-bit datatype.
See How to convert Strings to and from UTF8 byte arrays in Java on how to convert a byte[] to String with UTF-8 encoding.
Sending a java.lang.String over the wire is probably the wrong approach here, since Strings are always 16-bit (since Java was designed for globalization and stuff). If your radio library allows you to pass a byte[] instead of a String, that will allow you to send 8-bit values without needing to worry about converting to UTF8. As far as converting from an int to an unsigned byte, you'll probably want to look at this article.
int to array of bytes
public byte[] intToByteArray(int num){
byte[] intBytes = new byte[4];
intBytes[0] = (byte) (num >>> 24);
intBytes[1] = (byte) (num >>> 16);
intBytes[2] = (byte) (num >>> 8);
intBytes[3] = (byte) num;
return intBytes;
}
note endianness here is big endian.

Categories