问题描述
我希望能够将字符串(带有单词/字母)转换为其他形式,例如二进制.我将如何去做这件事.我正在使用 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
这篇关于在Java中将字符串(如testing123)转换为二进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)