【问题标题】:What is the proper implementation of building a string representation of the contents of a byte array?构建字节数组内容的字符串表示的正确实现是什么?
【发布时间】:2023-02-11 20:29:54
【问题描述】:

使用以下方法附加字符串生成器会产生不正确的结果。字节数组中的字节与结果字符串中表示的“1”和“0”不匹配。

InputStream is = new FileInputStream(bout);
StringBuilder sb = new StringBuilder();
byte[] a = is.readAllBytes();
for (byte b : a) {
  for (int i = 0; i < 8; i++) {
    sb.append((b & (1 << i)) != 0 ? '1' : '0');
  }
}
is.close();

我是否错误地使用了按位操作?

例如:

10111001

回报

10011101

【问题讨论】:

    标签: java bit bitwise-operators bit-shift bitwise-and


    【解决方案1】:

    它只是从后到前,你打印的第一位应该是最高位,即对应于 2^7 (128)。

    for (int i = 0; i < 8; i++) {
     sb.append((b & (128 >> i)) != 0 ? '1' : '0');
    }
    

    或者

    for (int i = 7; i >= 0; i--) {
     sb.append((b & (1 << i) != 0 ? '1' : '0');
    }
    

    【讨论】:

      猜你喜欢
      • 2016-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-12
      相关资源
      最近更新 更多