Java initialization string from hexadecimal array

Is it possible to initialize a String from an array of hexadecimal values, such as C style?

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

Why is it impossible to do something like this?

 String charArray = new String((byte[]) {0x41, 0x42, 0x43}); 
+4
source share
3 answers

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

  • Using unicode screens:

     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 should remember is that the string is not an array of something, it is a separate object. Therefore, it must be created as a string literal or with one of the constructors.

+3
source

The problem is not in String , but in Java arrays, and in particular in bytes.

You can do

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

or, better yet, you can just write String more literally with ASCII screens, etc.

 "\u0041\u0042\u0043" 
+2
source

There are no unsigned types in Java, so your array should contain the usual char values. However, numeric literals are int by default, so you may need to drop your values ​​to char , for example: (char)0x41 . The same applies to byte values ​​(use one or another option depending on whether your numbers are ASCII or Unicode BMP values). You can also use unicode escape code, for example String str = "\u0041\u0042"; . To get the byte representation of an ASCII string (or otherwise encoded) (the opposite operation), use the syntax, for example: String charArray = "abcd".getBytes("UTF-8"); .

Also note the difference between bytes and characters. A character is well defined by the Unicode standard and always has the same meaning. The byte value depends on the character encoding used, so you cannot just make a string of bytes. If you use the String(byte[]) constructor String(byte[]) , you use non-standard platform coding - this can be dangerous in some situations. String(char[]) , on the other hand, is safe (but if you generate char values ​​by casting hexadecimal numbers to char s, you de facto manually convert from ASCII).

+1
source

Source: https://habr.com/ru/post/1400459/


All Articles