java 将包含二进制值的字符串转换为十六进制

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

Translating a String containing a binary value to Hex

javastringbinaryhex

提问by Yuri

I am trying to translate a String that contains a binary value (e.g. 000010001010011) to it's Hex value.(453)

我正在尝试将包含二进制值(例如 000010001010011)的字符串转换为它的十六进制值。(453)

I've been trying several options, but mostly I get a converted value of each individual character. (0=30 1=31)

我一直在尝试几种选择,但大多数情况下我都会得到每个字符的转换值。(0=30 1=31)

I have a function that translates my input to binary code through a non-mathematical way, but through a series of "if, else if" statements. (the values are not calculated, because they are not standard.) The binary code is contained in a variable String "binOutput"

我有一个函数可以通过非数学方式将我的输入转换为二进制代码,但是通过一系列“if, else if”语句。(这些值不是计算出来的,因为它们不是标准的。)二进制代码包含在变量字符串“binOutput”中

I currently have something like this:

我目前有这样的事情:

        String bin = Integer.toHexString(Integer.parseInt(binOutput));

But this does not work at all.

但这根本行不通。

回答by Ted Hopp

Try using Integer.parseInt(binOutput, 2)instead of Integer.parseInt(binOutput)

尝试使用Integer.parseInt(binOutput, 2)代替Integer.parseInt(binOutput)

回答by jcomeau_ictx

Ted Hopp beat me to it, but here goes anyway:

泰德霍普打败了我,但无论如何:

jcomeau@intrepid:/tmp$ cat test.java; java test 000010001010011
public class test {
 public static void main(String[] args) {
  for (int i = 0; i < args.length; i++) {
   System.out.println("The value of " + args[i] + " is " +
    Integer.toHexString(Integer.parseInt(args[i], 2)));
  }
 }
}
The value of 000010001010011 is 453