在Java中是将整数值转换为“ n”位数字ASCII字节数组的任何方法。喜欢
IntToBytes( int value, int digits );
int a = 1234;
IntToBytes( a, 4 );
results will be byte array of {1, 2, 3, 4}
IntToBytes( a, 5 );
results will be byte array of {0, 1, 2, 3, 4}
我在互联网上搜索未找到任何方法。请帮我
如果要获取一个以十进制表示的数字值组成的数组,则可以创建一个类似以下的函数:
public static byte[] intToBytes(int number, int digits) {
byte[] results = new byte[digits];
/* Start at the end of the array. i.e. 1234, should be converted to {1, 2, 3, 4} */
for (int i = digits - 1; i >= 0; i--) {
results[i] = (byte) (number % 10);
number = number / 10;
}
return results;
}
如果您想要的是一个具有每个数字的ascii值的数组,则可以使用String.format
并将String转换为字节数组。
(1234应转换为{'1','2','3','4'}。ascii值应为{49、50、51、52}
代码可以是:
public static byte[] intToBytes(int number, int digits) {
String format = "%0" + digits + "d";
String numberAsString = String.format(format, number);
char[] numberAsCharArray = numberAsString.toCharArray();
byte[] result = new byte[digits];
for (int i = 0; i < numberAsCharArray.length; i++) {
result[i] = (byte) numberAsCharArray[i];
}
return result;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句