java 在java中将String / char转换为指定数字的二进制字符串,反之亦然

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

Convert String / char into specified-digit binary string and vice versa in java

javastringbinarychar

提问by tugcem

I'm trying to convert a string (or a single char) into given number of digits binary string in java. Assume that given number is 5, so a string "zx~q" becomes 01101, 10110, 11011, 10011 (I' ve made up the binaries). However, I need to revert these binaries into "abcd" again. If given number changes, the digits (so the binaries) will change.

我正在尝试在 java 中将字符串(或单个字符)转换为给定位数的二进制字符串。假设给定的数字是 5,那么字符串“zx~q”就变成了 01101、10110、11011、10011(我已经编好了二进制文件)。但是,我需要再次将这些二进制文件恢复为“abcd”。如果给定的数字发生变化,数字(二进制​​)也会发生变化。

Anyone has an idea?

有人有想法吗?

PS: Integer.toBinaryString()changes into an 8-digit binary array.

PS:Integer.toBinaryString()变成8位二进制数组。

回答by SirPentor

Looks like Integer.toString(int i, int radix)and Integer.parseInt(string s, int radix)would do the trick.

看起来Integer.toString(int i, int radix)并且Integer.parseInt(string s, int radix)会做到这一点。

回答by Ajay S

You can achieve like this.

你可以这样实现。

To convert abcdto 1010101111001101,

要将abcd转换为 1010101111001101,

class Demo {
    public static void main(String args[]) {  
        String str = "abcd";
        for(int i = 0; i < str.length(); i++) {
            int number = Integer.parseInt(String.valueOf(str.charAt(i)), 16);
            String binary = Integer.toBinaryString(number);
            System.out.print(binary);
        }
    }
}

To convert the 1010101111001101 to abcd

将 1010101111001101 转换为 abcd

String str = "1010101111001101";
String binary = Long.toHexString(Long.parseLong(str,2));
System.out.print(binary);