Convert a String of Hex into Ascii in Java

Convert a String of Hex into ASCII in Java

Just use a for loop to go through each couple of characters in the string, convert them to a character and then whack the character on the end of a string builder:

String hex = "75546f7272656e745c436f6d706c657465645c6e667375635f6f73745f62795f6d757374616e675c50656e64756c756d2d392c303030204d696c65732e6d7033006d7033006d7033004472756d202620426173730050656e64756c756d00496e2053696c69636f00496e2053696c69636f2a3b2a0050656e64756c756d0050656e64756c756d496e2053696c69636f303038004472756d2026204261737350656e64756c756d496e2053696c69636f30303800392c303030204d696c6573203c4d757374616e673e50656e64756c756d496e2053696c69636f3030380050656e64756c756d50656e64756c756d496e2053696c69636f303038004d50330000";
StringBuilder output = new StringBuilder();
for (int i = 0; i < hex.length(); i+=2) {
String str = hex.substring(i, i+2);
output.append((char)Integer.parseInt(str, 16));
}
System.out.println(output);

Or (Java 8+) if you're feeling particularly uncouth, use the infamous "fixed width string split" hack to enable you to do a one-liner with streams instead:

System.out.println(Arrays
.stream(hex.split("(?<=\\G..)")) //https://stackoverflow.com/questions/2297347/splitting-a-string-at-every-n-th-character
.map(s -> Character.toString((char)Integer.parseInt(s, 16)))
.collect(Collectors.joining()));

Either way, this gives a few lines starting with the following:

uTorrent\Completed\nfsuc_ost_by_mustang\Pendulum-9,000 Miles.mp3

Hmmm... :-)

How to convert Hexadecimal to ASCII values in java?

Something like this?

byte[] bytes = {0x31, 0x32, 0x2E, 0x30, 0x31, 0x33};
String result = new String(bytes, "ASCII");
System.out.println(result);

how to convert Hex String to ASCII String in KOTLIN

You're nearly there. You just need to convert the ByteArray to a String. The standard toString() method comes from type Any (equivalent to Java's Object). The ByteArray doesn't override it to give you what you want. Instead, use the String constructor or the toString(Charset) function:

fun String.decodeHex(): String {
require(length % 2 == 0) {"Must have an even length"}
return chunked(2)
.map { it.toInt(16).toByte() }
.toByteArray()
.toString(Charsets.ISO_8859_1) // Or whichever encoding your input uses
}

(Note also that require is more appropriate than check in that context.)

ASCII to HEX string in Java returns ASCII value and not HEX

There is nothing in your code that converts the byte you are getting from the buffer to hexadecimal; the sb.append(int) method that you are calling converts it to decimal, not hexadecimal. One solution is to do this:

sb.append(String.format("%02X", bb.get()));

Note that you call your method "ASCII to hex", but you are not actually using ASCII - you are using UTF-8, which is not exactly the same as ASCII.

Java String HEX to String ASCII with accentuation

Consider

String hex = "6174656ec3a7c3a36f";                                  // AAA
ByteBuffer buff = ByteBuffer.allocate(hex.length()/2);
for (int i = 0; i < hex.length(); i+=2) {
buff.put((byte)Integer.parseInt(hex.substring(i, i+2), 16));
}
buff.rewind();
Charset cs = Charset.forName("UTF-8"); // BBB
CharBuffer cb = cs.decode(buff); // BBB
System.out.println(cb.toString()); // CCC

Which prints: atenção

Basically, your hex string represents the hexidecimal encoding of the bytes that represent the characters in the string atenção when encoded in UTF-8.

To decode:

  • You first have to go from your hex string to bytes (AAA)
  • Then go from bytes to chars (BBB) -- this is dependent on the encoding, in your case UTF-8.
  • The go from chars to a string (CCC)

Convert string representation of a hexadecimal byte array to a string with non ascii characters in Java

The stuff within the square brackets, seems to be characters encoded in UTF-8 but converted into a hexadecimal string in a weird way. What you can do is find each instance that looks like [0xc3] and convert it into the corresponding byte, and then create a new string from the bytes.

Unfortunately there are no good tools for working with byte arrays. Here's a quick and dirty solution that uses regex to find and replace these hex codes with the corresponding character in latin-1, and then fixes that by re-interpreting the bytes.

String bracketDecode(String str) {
Pattern p = Pattern.compile("\\[(0x[0-9a-f]{2})\\]");
Matcher m = p.matcher(str);
StringBuilder sb = new StringBuilder();
while (m.find()) {
String group = m.group(1);
Integer decode = Integer.decode(group);
// assume latin-1 encoding
m.appendReplacement(sb, Character.toString(decode));
}
m.appendTail(sb);
// oh no, latin1 is not correct! re-interpret bytes in utf-8
byte[] bytes = sb.toString().getBytes(StandardCharsets.ISO_8859_1);
return new String(bytes, StandardCharsets.UTF_8);
}

How to parse a string of hex into ascii equivalent in Swift 2

Using regular expression matching is one possible method to extract the
"hex numbers" from the string.
What you are looking for is an optional "0x", followed by exactly
2 hex digits. The corresponding regex pattern is "(0x)?([0-9a-f]{2})".

Then you can convert each match to a Character and finally concatenate
the characters to a String, quite similar to your "partial implementation". Instead of strtoul() you can use the UInt32
initializer

init?(_ text: String, radix: Int = default)

which is new in Swift 2.

The pattern has two "capture groups" (encloses in parentheses),
the first one matches the optional "0x", and the second one matches
the two hex digits, the corresponding range can be retrieved with
rangeAtIndex(2).

This leads to the following implementation which can handle all
your sample strings:

func hexStringtoAscii(hexString : String) -> String {

let pattern = "(0x)?([0-9a-f]{2})"
let regex = try! NSRegularExpression(pattern: pattern, options: .CaseInsensitive)
let nsString = hexString as NSString
let matches = regex.matchesInString(hexString, options: [], range: NSMakeRange(0, nsString.length))
let characters = matches.map {
Character(UnicodeScalar(UInt32(nsString.substringWithRange($0.rangeAtIndex(2)), radix: 16)!))
}
return String(characters)
}

(See Swift extract regex matches for an explanation for the conversion to NSString.)

Note that this function is quite lenient, it just searches for
2-digit hex strings and ignores all other characters, so this
would be accepted as well:

let str6 = "4d+-4c*/4e0x63"

Update for Swift 5.1:

func hexStringtoAscii(_ hexString : String) -> String {

let pattern = "(0x)?([0-9a-f]{2})"
let regex = try! NSRegularExpression(pattern: pattern, options: .caseInsensitive)
let nsString = hexString as NSString
let matches = regex.matches(in: hexString, options: [], range: NSMakeRange(0, nsString.length))
let characters = matches.map {
Character(UnicodeScalar(UInt32(nsString.substring(with: $0.range(at: 2)), radix: 16)!)!)
}
return String(characters)
}


Related Topics



Leave a reply



Submit