Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting hex (or binary) data into Java strings

Tags:

java

In C there is an escape sequence that lets you embed a hex (or binary) value into a string? Something like this.

String str = "12345" + "\x0B" + "Some additional text";

Is there a similar function in Java?

like image 872
Joe Cullity Avatar asked Jul 07 '13 19:07

Joe Cullity


People also ask

How does Java handle hexadecimal?

In Java programs, hexadecimal numbers are written by placing 0x before numbers.

What is hex string in Java?

Hex String – A Hex String is a combination of the digits 0-9 and characters A-F, just like how a binary string comprises only 0's and 1's. Eg: “245FC” is a hexadecimal string. Byte Array – A Java Byte Array is an array used to store byte data types only. The default value of each element of the byte array is 0.

What data type is hex in Java?

Java allows us to define numbers interpreted as hex (base 16) by using the 0x prefix, followed by an integer literal. The value 0xff is equivalent to 255 in unsigned decimal, -127 in signed decimal, and 11111111 in binary.

Is hex a 1 byte?

Each Hexadecimal character represents 4 bits (0 - 15 decimal) which is called a nibble (a small byte - honest!). A byte (or octet) is 8 bits so is always represented by 2 Hex characters in the range 00 to FF.


1 Answers

It's not clear what you're trying to achieve. A String in Java is just a sequence of UTF-16 code units (which usually means "a sequence of characters", but characters outside the Basic Multilingual Plane require two UTF-16 code units). If you need binary data in there as well, you shouldn't use a string.

Now you can include the Unicode character U+000B (line tabulation) in the string, using \u000b - but you need to make sure that's actually what you want to do.

If you're actually trying to mix text data and binary data, I'd encourage you not to do that - it's very easy to lose data or convert it badly. If you provide your actual requirements, we may be able to help you come up with a much better solution.

like image 189
Jon Skeet Avatar answered Sep 25 '22 12:09

Jon Skeet