【发布时间】:2014-05-11 22:55:54
【问题描述】:
所以,我看到了这段将 ascii 转换为二进制的代码:
String s = "foo";
byte[] bytes = s.getBytes();
StringBuilder binary = new StringBuilder();
for (byte b : bytes)
{
int val = b;
for (int i = 0; i < 8; i++)
{
binary.append((val & 128) == 0 ? 0 : 1);
val <<= 1;
}
binary.append(' ');
}
System.out.println("'" + s + "' to binary: " + binary);
在这种情况下,<<= 运算符的作用是什么?这段代码究竟是如何构建s 的二进制表示的?
【问题讨论】:
-
二进制是什么?那是什么“二进制表示”?注意你
.getBytes()没有指定编码;如果我.getBytes(StandardCharsets.UTF_16)我将获得与.getBytes(StandardCharsets.US_ASCII)不同的结果。 -
你的参考书是怎么说的?
标签: java string bitwise-operators