Java 将 int 转换为具有固定位数的二进制

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

Converting an int to a binary with a fixed number of bits

java

提问by giulio

What is the easiest way in java to get the binary representation of an integer as a binary number with a fixed number of bits (For example, if I want to convert 3 with 5 bits, then the result would be 00011). In matlab, I can just specify the number of bits as an argument.

java中将整数的二进制表示作为具有固定位数的二进制数的最简单方法是什么(例如,如果我想用5位转换3,那么结果将是00011)。在 matlab 中,我可以只指定位数作为参数。

回答by giulio

To convert n to numbOfBits of bits:

要将 n 转换为 numbOfBits 位:

public static String intToBinary (int n, int numOfBits) {
   String binary = "";
   for(int i = 0; i < numOfBits; ++i, n/=2) {
      switch (n % 2) {
         case 0:
            binary = "0" + binary;
         break;
         case 1:
            binary = "1" + binary;
         break;
      }
   }

   return binary;
}

回答by SilentKnight

If you want to convert an intinto its binary representation, you need to do this:

如果要将 anint转换为其二进制表示,则需要执行以下操作:

String binaryIntInStr = Integer.toBinaryString(int);

If you want to get the bit count of an int, you need to do this:

如果你想获得一个的位数int,你需要这样做:

int count = Integer.bitCount(int);

But you couldn't get the binary representation of an integer as a binary number with a fixed number of bits, for example, 7 has 3 bits, but you can't set its bit count 2 or 1. Because you won't get 7 from its binary representation with 2 or 1 bit count.

但是您无法将整数的二进制表示作为具有固定位数的二进制数,例如,7 有 3 位,但您不能将其位数设置为 2 或 1。因为您不会得到7 从其具有 2 位或 1 位计数的二进制表示。

回答by alfreema

This is a simple way:

这是一个简单的方法:

String binaryString = Integer.toBinaryString(number);
binaryString = binaryString.substring(binaryString.length() - numBits);

Where numberis the integer to convert and numBitsis the fixed number of bits you are interested in.

其中number是要转换的整数,numBits是您感兴趣的固定位数。