2

如果字节数组包含非ASCII字符,是否会创建字符串?

String s  = new String(byte[] b)
4

3 回答 3

1

将单个字节解释为 ascii 字符,很容易拒绝低于 32 和高于 126 的值。

public static boolean isPrintableAscii(byte value)
{
    return (value > 32 ) && (value < 127);
}

public static String readableText(byte[] buffer, int offset, int bufferSize)
{
    StringBuilder builder = new StringBuilder();
    for( int index = 0; index < bufferSize; ++index)
    {
        byte current = buffer[offset+index];
        if( isPrintableAscii(current))
        {
            builder.append((char)current);
        }
        else
        {
            builder.append('.');
        }
    }

    return builder.toString();
}

当遇到不可打印的字节时,我只打印一个'。' 被十六进制转储实用程序使用了很长时间。

于 2014-04-14T18:17:24.523 回答
0

您可以使用new String (byte[] data, String charsetName)传递第二个参数作为US-ASCII

于 2012-06-16T04:38:23.210 回答
-1

No, it will not fail. However, there ways to detect non-ascii characters in a string and remove them. But Strings with non-ascii characters are perfectly fine.

于 2012-06-16T04:44:36.610 回答