Java 如何将字节数组中的数据打印为字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6463580/
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-08-16 06:10:15  来源:igfitidea点击:

how to print the data in byte array as characters

java

提问by

In my byte array i have the hash values of a message which consists of some negative values and also positive values. Positive values are being printed easily by using the (char)byte[i]statement. Now how can i get the negative value

在我的字节数组中,我有一条消息的哈希值,它由一些负值和正值组成。使用该(char)byte[i]语句可以轻松打印正值。现在我怎样才能得到负值

采纳答案by Jon Skeet

Well if you're happy printing it in decimal, you could just make it positive by masking:

好吧,如果你喜欢用十进制打印它,你可以通过屏蔽来使它成为正数:

int positive = bytes[i] & 0xff;

If you're printing out a hash though, it would be more conventional to use hex. There are plenty of other questions on Stack Overflow addressing converting binary data to a hex string in Java.

但是,如果您要打印散列,则使用十六进制会更传统。关于 Stack Overflow 解决在 Java 中将二进制数据转换为十六进制字符串的问题还有很多其他问题。

回答by alphazero

byte[] buff = {1, -2, 5, 66};
for(byte c : buff) {
    System.out.format("%d ", c);
}
System.out.println();

gets you

得到你

1 -2 5 66 

回答by Bohemian

How about Arrays.toString(byteArray)?

怎么样Arrays.toString(byteArray)

Here's some compilable code:

这是一些可编译的代码:

byte[] byteArray = new byte[] { -1, -128, 1, 127 };
System.out.println(Arrays.toString(byteArray));

Output:

输出:

[-1, -128, 1, 127]

Why re-invent the wheel...

为什么要重新发明轮子...

回答by Peter Lawrey

If you want to print the bytes as chars you can use the String constructor.

如果要将字节打印为字符,可以使用 String 构造函数。

byte[] bytes = new byte[] { -1, -128, 1, 127 };
System.out.println(new String(bytes, 0));

回答by Vinit Prajapati

Try this one : new String(byte[])

试试这个: new String(byte[])

回答by Robust

Try it:

尝试一下:

public static String print(byte[] bytes) {
    StringBuilder sb = new StringBuilder();
    sb.append("[ ");
    for (byte b : bytes) {
        sb.append(String.format("0x%02X ", b));
    }
    sb.append("]");
    return sb.toString();
}

Example:

例子:

 public static void main(String []args){
    byte[] bytes = new byte[] { 
        (byte) 0x01, (byte) 0xFF, (byte) 0x2E, (byte) 0x6E, (byte) 0x30
    };

    System.out.println("bytes = " + print(bytes));
 }

Output: bytes = [ 0x01 0xFF 0x2E 0x6E 0x30 ]

输出: bytes = [ 0x01 0xFF 0x2E 0x6E 0x30 ]