在 Java 中将字符串(如 testing123)转换为二进制 [英] Convert A String (like testing123) To Binary In Java

查看:30
本文介绍了在 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 

这篇关于在 Java 中将字符串(如 testing123)转换为二进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆