string to byte then byte[] 0xformat

2019-08-18 06:02发布

问题:

I am having problems of conversion through string->byte->byte[]

What I have done so far:

     double db = 1.00;
     double ab = db*100;
     int k = (int) ab;

     String aa = String.format("%06d", k);

     String first = aa.substring(0,2);``
     String second = aa.substring(2,4);
     String third = aa.substring(4,6);

     String ff = "0x"+first;
     String nn = "0x"+second;
     String yy = "0x"+third;

I want to write those bytes to an byte[]. What I mean is:

byte[] bytes = new byte[]{(byte) 0x02, (byte) 0x68, (byte) 0x14,
    (byte) 0x93, (byte) 0x01, ff,nn,yy};

in this order and casted with 0x's. Any help is greatly appriciated.

Regards, Ali

回答1:

You can use Byte.decode()

Decodes a String into a Byte. Accepts decimal, hexadecimal, and octal numbers given by the following grammar:

DecodableString:
    Signopt DecimalNumeral 
    Signopt 0x HexDigits 
    Signopt 0X HexDigits 
    Signopt # HexDigits 
    Signopt 0 OctalDigits

Below code will print 10, 11 which is value of 0XA, 0XB

    byte[] temp = new byte[2];
    temp[0] = Byte.decode("0xA");
    temp[1] = Byte.decode("0xB");
    System.out.println(temp[0]);
    System.out.println(temp[1]);


回答2:

As I see, the main question here is how to convert a 2 char String representing a hexa number to a byte type. The Byte class has a static method parseByte(String s, int radix) that can parse a String to number using the radix you want (in this case, 16). Here is an example of how you can do the parsing and save the result in a byte array:

public static void main(String [] args){
    System.out.println(Arrays.toString(getBytes("0001020F")));
}


public static byte[] getBytes(String str) {

    byte [] result = new byte[str.length() / 2]; //assuming str has even number of chars...

    for(int i = 0; i < result.length; i++){
        int startIndex = i * 2;
        result[i] = Byte.parseByte(str.substring(startIndex, startIndex + 2), 16);
    }
    return result;
}