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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/917163/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:02:16  来源:igfitidea点击:

Convert A String (like testing123) To Binary In Java

javabinaryasciihex

提问by

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

我希望能够将字符串(带有单词/字母)转换为其他形式,如二进制。我将如何去做这件事。我在 BLUEJ (Java) 中编码。谢谢

回答by erickson

A Stringin Java can be converted to "binary" with its getBytes(Charset)method.

StringJava 中的A可以通过其getBytes(Charset)方法转换为“二进制” 。

byte[] encoded = "こんにちは、世界!".getBytes(StandardCharsets.UTF_8);

The argument to this method is a "character-encoding"; this is a standardized mapping between a character and a sequence of bytes. Often, each character is encoded to a single byte, but there aren't enough unique byte values to represent every character in every language. Other encodings use multiple bytes, so they can handle a wider range of characters.

此方法的参数是“字符编码”;这是字符和字节序列之间的标准化映射。通常,每个字符都被编码为一个字节,但没有足够的唯一字节值来表示每种语言中的每个字符。其他编码使用多个字节,因此它们可以处理更广泛的字符。

Usually, the encoding to use will be specified by some standard or protocol that you are implementing. If you are creating your own interface, and have the freedom to choose, "UTF-8" is an easy, safe, and widely supported encoding.

通常,要使用的编码将由您正在实施的某些标准或协议指定。如果您正在创建自己的界面,并且可以自由选择,“UTF-8”是一种简单、安全且得到广泛支持的编码。

  • It's easy, because rather than including some way to note the encoding of each message, you can default to UTF-8.
  • It's safe, because UTF-8 can encode anycharacter that can be used in a Java character string.
  • It's widely supported, because it is one of a small handful of character encodings that is required to be present in any Java implementation, all the way down to J2ME. Most other platforms support it too, and it's used as a default in standards like XML.
  • 这很容易,因为您可以默认使用 UTF-8,而不是包含某种方式来记录每条消息的编码。
  • 这是安全的,因为 UTF-8 可以编码可以在 Java 字符串中使用的任何字符。
  • 它得到了广泛的支持,因为它是任何 Java 实现中都需要出现的少数字符编码之一,一直到 J2ME。大多数其他平台也支持它,并且在 XML 等标准中用作默认值。

回答by Nuoji

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).

通常的方法是使用String#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).

请注意,getBytes()使用默认字符集,因此如果您希望将字符串转换为某些特定的字符编码,则应getBytes(String encoding)改为使用,但很多时候(尤其是在处理 ASCII 时)getBytes()就足够了(并且具有不抛出已检查异常的优点)。

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 

回答by Peter Lawrey

A shorter example

一个较短的例子

private static final Charset UTF_8 = Charset.forName("UTF-8");

String text = "Hello World!";
byte[] bytes = text.getBytes(UTF_8);
System.out.println("bytes= "+Arrays.toString(bytes));
System.out.println("text again= "+new String(bytes, UTF_8));

prints

印刷

bytes= [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]
text again= Hello World!

回答by siva

public class HexadecimalToBinaryAndLong{
  public static void main(String[] args) throws IOException{
    BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter the hexa value!");
    String hex = bf.readLine();
    int i = Integer.parseInt(hex);               //hex to decimal
    String by = Integer.toBinaryString(i);       //decimal to binary
    System.out.println("This is Binary: " + by);
    }
}

回答by janu

import java.lang.*;
import java.io.*;
class d2b
{
  public static void main(String args[]) throws IOException{
  BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
  System.out.println("Enter the decimal value:");
  String h = b.readLine();
  int k = Integer.parseInt(h);  
  String out = Integer.toBinaryString(k);
  System.out.println("Binary: " + out);
  }
}   

回答by Vincent Vieira

You can also do this with the ol' good method :

您也可以使用 ol' good 方法执行此操作:

String inputLine = "test123";
String translatedString = null;
char[] stringArray = inputLine.toCharArray();
for(int i=0;i<stringArray.length;i++){
      translatedString += Integer.toBinaryString((int) stringArray[i]);
}

回答by Barry H.

While playing around with the answers I found here to become familiar with it I twisted Nuoji's solution a bit so that I could understand it faster when looking at it in the future.

在玩弄我在这里找到的答案以熟悉它时,我稍微扭曲了诺吉的解决方案,以便我在将来查看它时可以更快地理解它。

public static String stringToBinary(String str, boolean pad ) {
    byte[] bytes = str.getBytes();
    StringBuilder binary = new StringBuilder();
    for (byte b : bytes)
    {
       binary.append(Integer.toBinaryString((int) b));
       if(pad) { binary.append(' '); }
    }
    return binary.toString();        
}

回答by Jay Remy

Here are my solutions. Their advantages are : easy-understanding code, works for all characters. Enjoy.

这是我的解决方案。它们的优点是:易于理解的代码,适用于所有字符。享受。

Solution 1 :

解决方案1:

public static void main(String[] args) {

    String str = "CC%";
    String result = "";
    char[] messChar = str.toCharArray();

    for (int i = 0; i < messChar.length; i++) {
        result += Integer.toBinaryString(messChar[i]) + " ";
    }

    System.out.println(result);
}

prints :

印刷 :

1000011 1000011 100101

Solution 2 :

解决方案2:

Possibility to choose the number of displayed bits per char.

可以选择每个字符显示的位数。

public static String toBinary(String str, int bits) {
    String result = "";
    String tmpStr;
    int tmpInt;
    char[] messChar = str.toCharArray();

    for (int i = 0; i < messChar.length; i++) {
        tmpStr = Integer.toBinaryString(messChar[i]);
        tmpInt = tmpStr.length();
        if(tmpInt != bits) {
            tmpInt = bits - tmpInt;
            if (tmpInt == bits) {
                result += tmpStr;
            } else if (tmpInt > 0) {
                for (int j = 0; j < tmpInt; j++) {
                    result += "0";
                }
                result += tmpStr;
            } else {
                System.err.println("argument 'bits' is too small");
            }
        } else {
            result += tmpStr;
        }
        result += " "; // separator
    }

    return result;
}


public static void main(String args[]) {
    System.out.println(toBinary("CC%", 8));
}

prints :

印刷 :

01000011 01000011 00100101

回答by Nicholas Strydom

This is my implementation.

这是我的实现。

public class Test {
    public String toBinary(String text) {
        StringBuilder sb = new StringBuilder();

        for (char character : text.toCharArray()) {
            sb.append(Integer.toBinaryString(character) + "\n");
        }

        return sb.toString();

    }
}

回答by pruthwiraj.kadam

       int no=44;
             String bNo=Integer.toString(no,2);//binary output 101100
             String oNo=Integer.toString(no,8);//Oct output 54
             String hNo=Integer.toString(no,16);//Hex output 2C

              String bNo1= Integer.toBinaryString(no);//binary output 101100
              String  oNo1=Integer.toOctalString(no);//Oct output 54
              String  hNo1=Integer.toHexString(no);//Hex output 2C

              String sBNo="101100";
              no=Integer.parseInt(sBNo,2);//binary to int output 44

              String sONo="54";
              no=Integer.parseInt(sONo,8);//oct to int  output 44

              String sHNo="2C";
              no=Integer.parseInt(sHNo,16);//hex to int output 44