How to append a byte to a string in Java?

16,282

Solution 1

If you want to concatenate the actual value of a byte to a String use the Byte wrapper and its toString() method, like this:

String someString = "STRING";
byte someByte = 0x10;
someString += Byte.toString(someByte);

Solution 2

If you just want to extend a String literal, then use this one:

System.out.println("Hello World\u0010");

otherwise:

String s1 = "Hello World";
String s2 = s1 + '\u0010';

And no - character are not bytes and vice versa. But here the approximation is close enough :-)

Solution 3

If you want to have the String representation of the byte as ascii char then try this:

public static void main(String[] args) {
    String a = "bla";

    byte x = 0x21; // Ascii code for '!'

    a += (char)x;

    System.out.println(a); // Will print out 'bla!'
}

If you want to convert the byte value into it's hex representation as String then take a look at Integer.toHexString

Share:
16,282
Justin
Author by

Justin

Hi. My name is Justin. I recently graduated from the University of Waterloo in Waterloo, ON, Canada with a Bachelor of Applied Science in Computer Engineering. I aspire to continue developing my skills in software and embedded systems development.

Updated on June 05, 2022

Comments

  • Justin
    Justin over 1 year

    I have this operation I need to perform where I need to append a byte such as 0x10 to some String in Java. I was wondering how I could go about doing this?

    For example:

    String someString = "HELLO WORLD";
    byte someByte = 0x10;
    

    In this example, how would I go about appending someByte to someString?

    The reason why I am asking this question is because the application I am developing is supposed to send commands to some server. The server is able to accept commands (base64 encoded), decode the command, and parse out these bytes that are not necessarily compatible with any sort of ASCII encoding standard for performing some special function.