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

查看:288
本文介绍了将一个字符串转换(比如是testing123)二进制在Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够转换一个字符串(文字/字母),以其他形式,如二进制文件。
我怎么会去这样做。我编码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

推荐答案

通常的方法是使用字符串#的getBytes()来获取潜在的字节,然后present这些字节以其他形式(十六进制,二进制等等)。

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(字符串编码)来代替,但很多时候(尤指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);

运行这个例子将产生:

Running this example will yield:

'foo' to binary: 01100110 01101111 01101111

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

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