简体   繁体   中英

java: convert a string to a string that contains the hex number of each character

I have a string that actually each byte in it is a representation of a hexadecimal number.

I want to create a new string that contains the actual hexadecimal numbers of each character.

I know that i can do String.getBytes() to get the bytes of each character, i know iterate through it with i=0;i<=String.getBytes().length . what i don't understand is how to create a new string that each character is the hexacdecimal number (0-F).

thanks!

You could do something like

String test = "hello world", result = "";

for (byte b : test.getBytes())
    result += Integer.toHexString(b) + " ";

System.out.println(result);

// result = 68 65 6c 6c 6f 20 77 6f 72 6c 64 

Keep in mind though, that strings in Java are in unicode.

There are a few misconceptions - or at least problematic descriptions - in your post:

  • Strings consist of characters , not bytes
  • Numbers aren't hexadecimal or decimal etc; their representations are hex etc

You're then calling String.getBytes() , but it's not clear what encoding you want to use. As stated before, a String is a sequence of characters . To convert that into bytes , you need to apply an encoding. Unfortunately, String.getBytes() uses the "platform default encoding" which is almost never a good choice. You should always specify which encoding you want to use.

When you have converted the String into bytes (if you definitely want to do that) it's easy to convert that to hex:

for (byte b : test.getBytes("UTF-8"))
{
    int x = b & 0xff; // I suspect you don't want negative numbers
    System.out.println(Integer.toHexString(b));
}

Alternatively you might want to convert each Unicode character to its hex representation:

for (char c : test.toCharArray())
{
    System.out.println(Integer.toHexString(c));
}

Note that Integer.toHexString doesn't pad its output to a particular number of characters.

If you could give more information about your input and expected output, that would really help.

  • commons-codec has Hex.encode(byteArray)
  • you can also use Integer.toHexString(..) for each byte

Just be careful when obtaining the bytes. Use the method getBytes(ecnoding) instead of the one without arguments which takes the platform encoding.

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