問題描述
我希望能夠?qū)⒆址?帶有單詞/字母)轉(zhuǎn)換為其他形式,例如二進制.我將如何去做這件事.我正在使用 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()
獲取底層字節(jié),然后以其他形式呈現(xiàn)這些字節(jié)(十六進制,二進制無論如何).
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()
使用默認字符集,因此如果要將字符串轉(zhuǎn)換為某種特定的字符編碼,則應使用 getBytes(String encoding)
代替,但很多時候(尤其是在處理 ASCII 時)getBytes()
就足夠了(并且具有不拋出已檢查異常的優(yōu)點).
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).
具體轉(zhuǎn)換成二進制,這里舉個例子:
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);
運行此示例將產(chǎn)生:
'foo' to binary: 01100110 01101111 01101111
這篇關于在Java中將字符串(如testing123)轉(zhuǎn)換為二進制的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!