简体   繁体   中英

how to create a byte from string representation of a byte

i am working on a project(web application with java 2 ee) and i need to send an OutputStream on a COM port, the data type in the OutputStream is byte[] , one byte of this data is the address of the destination hardware which i am trying to communicate with . problem is the address of the hardware has to be provided by the user within a web page. so how can i convert the string representation of a byte into a real byte ? i hope the following code can make the problem more vivid

String data1 = "0xA1";
String data2 = "0xAB";

and i need to put the following line in OutputStream.

byte[] b = new byte[]{0xA1,0xAB};

some say using org.apache.commons.codec.binary.Base64 can solve the problem but i don't have any clue . thank you in advance.

It's easy:

byte b = Integer.decode("0xA1").byteValue();

Link to javadoc .

you can use the below method in order to convert a String to its byte value representation, but you need to send it only the part of the String without the "0x"

public static byte convertStringToByte(String str){
    return (byte)Integer.parseInt(str, 16);
}

If you want to have fun in doing it yourself instead of doing it through a function call
do it like below

Get the ASCII value
Divide it by 2 collect the reminder (which will be 1 or 0 )
Finally reverse the whole sequence

For example, for decimal 32 you should get 0100000

If you are initializing the COM port, you can also some sequences (ASCII sequences)
directly instead of binary, check the manual.

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