简体   繁体   English

Java核心如何将20个字节的字节数组转换为字符串

[英]Core Java How to convert 20 byte byte array to a string

I am getting input 20 byte . 我正在输入20个字节。 The charset used is UTF-8 使用的字符集为UTF-8

when I convert it as string, I see 0000000000000000000000000000000000000000 当我将其转换为字符串时,我看到0000000000000000000000000000000000000000000000

this is correct. 这是对的。

But when I convert it to string, I get a empty value. 但是,当我将其转换为字符串时,会得到一个空值。 I suspect charset as problem, but even after trying different charSets, I could not return the value '0'. 我怀疑字符集是问题,但是即使尝试了不同的字符集,我也无法返回值“ 0”。

public String convertFromBytes(byte[] input) {
    System.out.println("BYTES ARE =="+ Hex.encodeHexString(input));
    System.out.println("VALUE IS "+ new String(input, this.charset));
    return new String(input, this.charset);
}

I tried changing charSet but not able to solve it, Any clues what I might be missing. 我尝试更改charSet但无法解决它,任何提示我可能会缺少的线索。

US-ASCII 美国ASCII
ISO-8859-1 ISO-8859-1
UTF-8 UTF-16BE UTF-16LE UTF-16 UTF-8 UTF-16BE UTF-16LE UTF-16

I have not tested the code. 我没有测试代码。

AI understand, you try to convert {0x00, 0x00, 0x00...} to "000..." , but you get nothing. AI理解,您尝试将{0x00, 0x00, 0x00...}"000..." ,但您一无所获。 Since the value of '0' , as a character is not 0 but (ASCII) 48 , this wont print anything. 由于'0'的值(作为字符)不是0而是(ASCII) 48 ,因此不会打印任何内容。 There is a difference between dumping a hex value, and interpreting an array of hexadecimals as a string with encoding. 转储十六进制值与将十六进制数组解释为具有编码的字符串之间有区别。

Try with {48, 48, 48...} , the string will be "000000.." , but the hex writeline will produce "48484848..." , or something like that. 尝试使用{48, 48, 48...} 48,48,48 {48, 48, 48...} ,字符串将为"000000.." ,但十六进制写行将产生"48484848..."或类似的东西。

PS: The code for '0' is 48 in base 10 . PS: 以10底的 '0'代码为48

Edit: It seems your string is not empty, just contains non-printable characters. 编辑:似乎您的字符串不是空的,只包含不可打印的字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM