繁体   English   中英

您可以将包含不可打印字符的字节数组转换为字符串吗?

[英]Can you convert a byte array containing non printable characters to a string?

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

String s  = new String(byte[] b)

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

将单个字节解释为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();
}

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

不,它不会失败。 但是,有一些方法可以检测字符串中的非ASCII字符并将其删除。 但是带有非ASCII字符的字符串完全可以。

暂无
暂无

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

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