在Java中将字符串(如testing123)转换为二进制

Convert A String (like testing123) To Binary In Java(在Java中将字符串(如testing123)转换为二进制)
本文介绍了在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)转换为二进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Fastest way to generate all binary strings of size n into a boolean array?(将所有大小为 n 的二进制字符串生成为布尔数组的最快方法?)
Convert integer to zero-padded binary string(将整数转换为零填充的二进制字符串)
How Can I Convert Very Large Decimal Numbers to Binary In Java(如何在 Java 中将非常大的十进制数转换为二进制数)
Check if only one single bit is set within an integer (whatever its position)(检查整数中是否只设置了一个位(无论其位置如何))
Embed a Executable Binary in a shell script(在 shell 脚本中嵌入可执行二进制文件)
why does quot;STRINGquot;.getBytes() work different according to the Operation System(为什么“STRING.getBytes() 的工作方式因操作系统而异)