将字符串转换为二进制 [Java]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22753781/
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-13 17:42:36  来源:igfitidea点击:

Converting a string to binary [Java]

javastringbinary

提问by user3479783

Let's say I have the following string:

假设我有以下字符串:

String s = "Hello, stackoverflow"

How would I convert that into a binary number (0s and 1s)? Here's the trick: I'm not allowed to use built-in methods for the conversion. It has to be done mathematically. I have no idea where to begin. Can anyone point me in the right direction?

我如何将其转换为二进制数(0 和 1)?诀窍是:我不允许使用内置方法进行转换。它必须在数学上完成。我不知道从哪里开始。任何人都可以指出我正确的方向吗?

Edit 1: I've seen this questionand people suggested using getBytes(string), charset UTF-8, and Integer.toBinaryString. I'm not allowed to use any of these methods for conversion. I haven't heard of 36-base either.

编辑 1:我见过这个问题,人们建议使用 getBytes(string)、字符集 UTF-8 和 Integer.toBinaryString。我不允许使用任何这些方法进行转换。我也没有听说过 36-base。

回答by Pulah Nandha

First get bytes form string using getByte()function then use Integer.toBinaryString(byte)function. & thats it.

首先使用getByte()函数获取字节形式的字符串,然后使用 Integer.toBinaryString(byte)函数。& 就是这样。

NOTE:~ Make sure Integer.toBinaryString(byte)accepts int(or in this case byte not all.) so you have to pass byte by byte.(may be for loop.)

注意:~确保Integer.toBinaryString(byte)接受 int(或者在这种情况下不是全部字节。)所以你必须逐字节传递。(可能是 for 循环。)

Edited :~what you can do is parse string char by char & for each char you can get ascii value using.

编辑:~你可以做的是按字符解析字符串字符 & 为每个字符解析你可以使用的 ascii 值。

int tempChar = (int)ch;

Then simpley use this.

然后简单地使用这个。

Integer.toString(tempChar,2);

try this.

尝试这个。

string finalString = "";
for(int i = 0;i<myStr.length;i++){
    int tempChar = (int)ch;
    finalString = finalString + Integer.toString(tempChar,2);//& this is not allowed then now only you need to create function for integer to binary conversion.
}
System.out.println("Your byte String is"+finalString);

回答by Rahul Tripathi

You may try like this:-

你可以这样尝试:-

String s = "Hello, stackoverflow"
byte[] bytes = str.getBytes(s);

You may check the getBytes() methodin java

您可以检查java 中的getBytes() 方法

Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.

The behavior of this method when this string cannot be encoded in the given charset is unspecified. The CharsetEncoder class should be used when more control over the encoding process is required.

使用命名字符集将此 String 编码为字节序列,并将结果存储到新的字节数组中。

当此字符串无法在给定字符集中编码时,此方法的行为未指定。当需要对编码过程进行更多控制时,应使用 CharsetEncoder 类。

If you want the bits for each byte:

如果您想要每个字节的位:

for(int i=0; i<array.length;i++){
    System.out.println(Integer.toBinaryString(0x100 + array[i]).substring(1));
}

回答by Hungry Blue Dev

This seems a bit unfair because we can't use:

这似乎有点不公平,因为我们不能使用:

byte[] b = s.getBytes();

This is the shortest solution to your problem, but since you aren't supposed to use that, here's a badapproach:

这是解决您问题的最短方法,但由于您不应该使用它,因此这是一个糟糕的方法:

Using String#charAt(int):

使用String#charAt(int)

String s = "Hello, stackoverflow";
StringBuilder buf = new StringBuilder();
for (int i = 0; i < s.length(); i++ ) {
    int charcterASCII = s.charAt(i);
    // Automatic type casting as 'char' is a type of 'int'
    buf.append(Integer.toBinaryString(characterASCII);
    // or:
    // buf.append(characterASCII, 2);
    // or - custom method:
    // buf.append(toBinary(characterASCII));
}
System.out.println("answer : " + buf.toString());

And if you decide to use toBinary(int)method, here it is:

如果你决定使用toBinary(int)方法,这里是:

public static final String toBinary (int num) {
    char[] buf = new char[32];
    int charPos = 32;
    do {
        buf[--charPos] = i & 1;
        i >>>= 1;
    } while (i != 0);
    return new String(buf);
}

Or if even this is not allowed, you'd better make your own solution. :-)

或者,即使这也是不允许的,您最好制定自己的解决方案。:-)