我正在编写一个方法,我将int值转换为二进制字符串并存储它们.我使用Integer.toBinaryString方法这样做,并且它正常工作,但问题是我需要方法返回字符串中的4位而不是更少(它永远不会更多因为数字不够大).以下是我的代码示例以及问题发生的位置:
int value5 = 3;
String strValue5 = Integer.toBinaryString(value5);
for(int index = 0; index < 4; index++){
sBoxPostPass[4][index] = strVal5.charAt(index);
}
Run Code Online (Sandbox Code Playgroud)
显然,这将引发ArrayOutOfBoundsException因为strValue5 == 11不0011一样,它需要.我希望这很清楚.在此先感谢您的帮助.
如果您的值始终只有 4 位,那么它就足够小,可以使用查找表来查找相关的 16 个值。纠正 Java 中的任何错误将作为读者的练习。
static String binary4[16] = {"0000", /* another exercise for the reader */, "1111"};
static String toBinary4(int value) {
return binary4[value & 0xF];
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6944 次 |
| 最近记录: |