将 int 从位的十进制表示形式转换为本机位,而不使用 String? (Java)

Convert int from decimal representation of bits to native bits, without using String? (Java)

在我正在修改的代码中,有整数和整数 通过在代码中使用它们的十进制数字来表示 二进制文字,例如

int intDigitsAsBits = 1101;   // integer "representing" 13 to coder
int intDigitsAsBitsB = 1000;  // integer "representing" 8 to coder

Background: I am working with a Java dialect with pre-Java 7 aspects (Processing), such as the unavailability of 0b0000-style binary literals. I am developing native Java 8 libraries in this context -- not Processing code. The interface to Processing is for a community of primarily early code language learners, hence the approximation of binary in a visual form they can understand while typing.

我希望能够即时将这些伪二进制整数值转换为其本机表示形式,例如

int intDigitsAsBits = 1101;
int intNative = someUnDecimalMethod(intDigitsAsBits);
System.out.println(intNative);  // "13"

我已经有一种方法可以使用到 String 的中间转换,然后使用 radix=2 Integer.parseInt() 转换回来。

int intDigitsAsBits = 1101;
String iString = intDigitsAsBits + "";
int intBinaryValue = Integer.parseInt(iString, 2);
System.out.println(intBinaryValue);  // "13"

是否有 Java 解决方案可以将 int 或 Integer 的数字作为位格式转换为本机表示形式 -- 没有 使用 String 作为中间值?

我对效率特别感兴趣,但欢迎任何和所有解决方案。

好吧,要直接从数字形式转换为本机 int 形式,您可以执行以下操作:

int count =0;
int digitsAsBits = 1101;
int result =0;
while(digitsAsBits !=0){
    int lastdigit = digitsAsBits%10;
    result += lastdigit*Math.pow(2, count);
    count++;
    digitsAsBits = digitsAsBits/10;
}
int result = 0;
int i= 0;
while (bits != 0) {
    result |= (bits % 10) << i;
    i++;
    bits /= 10;
}