在Java中将字符串(如testing123)转换为二进制
我希望能够将字符串(带有单词/字母)转换为其他形式,例如二进制.我将如何去做这件事.我正在使用 BLUEJ (Java) 进行编码.谢谢
I would like to be able to convert a String (with words/letters) to other forms, like binary. How would I go about doing this. I am coding in BLUEJ (Java). Thanks
推荐答案
通常的方法是使用 String#getBytes()
获取底层字节,然后以其他形式呈现这些字节(十六进制,二进制无论如何).
The usual way is to use String#getBytes()
to get the underlying bytes and then present those bytes in some other form (hex, binary whatever).
请注意,getBytes()
使用默认字符集,因此如果要将字符串转换为某种特定的字符编码,则应使用 getBytes(String encoding)
代替,但很多时候(尤其是在处理 ASCII 时)getBytes()
就足够了(并且具有不抛出已检查异常的优点).
Note that getBytes()
uses the default charset, so if you want the string converted to some specific character encoding, you should use getBytes(String encoding)
instead, but many times (esp when dealing with ASCII) getBytes()
is enough (and has the advantage of not throwing a checked exception).
具体转换成二进制,这里举个例子:
For specific conversion to binary, here is an example:
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);
运行此示例将产生:
'foo' to binary: 01100110 01101111 01101111
相关文章