简体   繁体   中英

creating hex byte array in java

Here is the problem, I need to do it in Java: I need to create a byte array with hex values, to send via socket to a device. message format is something like this

STX cmd1 Arg1 , cmd2 ETX Checksum // Any number of commands and arguments

Example : STX A 1 ETX 148 // 1 and 148 are in decimal STX is 0x02 and ETX is 0x03 , not text STX and ETX.

The byte array which is to be generated for the above example is this :

 STX A 1 ETX 148
    {(byte)0x2,(byte)0x41,(byte)0x31,(byte)0x3, (byte)0x94}

Can you please help me. How do I do convert these numbers/characters and assign to byte array?

Unless I'm mistaken, you're already heading in the right direction.

A few things to know, an unsigned byte goes from 0 to 255 (0x00 to 0xFF). In Java, there are only signed data types and a byte goes from -128 to +127.

System.out.println(Byte.MIN_VALUE); // -128
System.out.println(Byte.MAX_VALUE); // +127

If fields 3 & 5 are int s casting them to byte s is fine, but know that anything that is over +127 when casted to a byte will overflow into the negative range.

System.out.println((byte)0x94); // -108
System.out.println((byte)148);  // -108

If you're wanting the actual positive value of the byte you can AND each byte against 0xFF.

System.out.println(((byte)-108) & 0xFF); // +148
System.out.println(((byte)-1) & 0xFF);   // +255

Couldn't you just use what Sotirios Delimanolis proposed in the comments and put your char variables in there?

char a = 'A';
char b = '1';
byte[] buffer = {(byte)0x2, (byte)a, (byte)b, (byte)0x3, (byte)0x94};

Or am I missing something here?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM