java 如何在Java中将一个字节附加到一个字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15977137/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 21:31:09  来源:igfitidea点击:

How to append a byte to a string in Java?

javastringhexbyte

提问by Justin

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?

我有这个操作我需要执行,我需要在 Java 中将一个字节(例如 0x10)附加到某个字符串。我想知道我怎么才能做到这一点?

For example:

例如:

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

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

在这个例子中,我将如何将 someByte 附加到 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.

我问这个问题的原因是因为我正在开发的应用程序应该向某个服务器发送命令。服务器能够接受命令(base64 编码),对命令进行解码,并解析出这些字节,这些字节不一定与任何类型的 ASCII 编码标准兼容,以执行某些特殊功能。

回答by Fritz

If you want to concatenate the actual value of a byteto a Stringuse the Bytewrapper and its toString()method, like this:

如果要将 a 的实际值连接byte到 aString使用Byte包装器及其toString()方法,如下所示:

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

回答by A.H.

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 :-)

没有 - 字符不是字节,反之亦然。但这里的近似值已经足够接近了:-)

回答by Nick Russler

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

如果您想将字节的字符串表示为 ascii 字符,请尝试以下操作:

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

如果要将字节值转换为字符串的十六进制表示形式,请查看Integer.toHexString