4

Is it possible to initialize a String from an array of hex values, like C style?

unsigned char[] charArray = {0x41, 0x42, 0x43};

Why is not possible to do something like this?

String charArray = new String((byte[]) {0x41, 0x42, 0x43});

3 Answers 3

3

It is perfectly possible, you can do it in several ways.

  • Using unicode escapes:

    String string = "\u0041\u0042\u0043";
    
  • Creating and using a byte array:

    String string = new String(new byte[] {(byte) 0x41, (byte) 0x42, (byte) 0x43});
    

The main thing you have to remember is that the string is not an array of something, it is a separate object. Therefore it should either be created as a string literal, or with one of the constructors.

Sign up to request clarification or add additional context in comments.

Comments

2

The problem isn't with String, it's with Java arrays and specifically bytes.

You can do

String charArray = new String(new byte[] {(byte) 0x41, (byte) 0x42,
  (byte) 0x43});

or, even better, you can just write the String more literally with ASCII escapes and the like.

"\u0041\u0042\u0043"

Comments

1

There are no unsigned types in Java, so your array must contain regular char values. However, numeric literals are by default of type int, so you may need to cast your values to char, like so: (char)0x41. Same goes for byte values (use one or the other depending on whether your numbers are ASCII or Unicode BMP values). You can also use the unicode escape, like String str = "\u0041\u0042";. To get a byte representation of an ASCII (or otherwise encoded) string (the opposite operation), use syntax such as: String charArray = "abcd".getBytes("UTF-8");.

Also, note the distinction between bytes and characters. A character is well-defined by Unicode standard and always has the same meaning. A byte's meaning depends on the character encoding used, so you can't just make a string out of bytes. If you use the String(byte[]) constructor, you are using your platform's default encoding implicitly - this may be risky in some situations. String(char[]) on the other hand is safe (but if you generate the char values by casting hex numbers to chars, you are de facto manually converting from ASCII).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.