获取int的ASCII码

时间:2014-07-12 03:43:30

标签: java byte

有没有"清洁"如何做到以下几点?

byte b;
int chLen = /*for example*/ (int)(Math.random() * 10);
b = ("" + (int)(char)chLen).getBytes()[0];

这基本上采用了> = 0且< 10并获取其ASCII码并将其存储到一个字节中,但看起来有一个更好的方法。任何想法???

3 个答案:

答案 0 :(得分:2)

也许您正在寻找类似n + '0'的内容,其中n是0到9之间的int

答案 1 :(得分:0)

下面怎么样:

byte[] bytes = ByteBuffer.allocate(4).putInt(chLen).array();

for (byte b : bytes) {
   System.out.format("0x%x ", b);
}

答案 2 :(得分:0)

听起来你想要一个从0到9的随机数,然后将它添加到'0',我会用Random.nextInt(10)得到这样的数字,

Random rand = new Random();
int ch = '0' + rand.nextInt(10);
System.out.printf("'%s' = %d (dec), %s (hex)%n",
    String.valueOf((char) ch), ch,
    Integer.toHexString(ch));

由于调试随机代码很困难,我还写了一个简单的单元测试,

for (int ch = '0'; ch <= '9'; ch++) {
  System.out.printf("'%s' = %d (dec), %s (hex)%n",
      String.valueOf((char) ch), ch,
      Integer.toHexString(ch));
}

输出

'0' = 48 (dec), 30 (hex)
'1' = 49 (dec), 31 (hex)
'2' = 50 (dec), 32 (hex)
'3' = 51 (dec), 33 (hex)
'4' = 52 (dec), 34 (hex)
'5' = 53 (dec), 35 (hex)
'6' = 54 (dec), 36 (hex)
'7' = 55 (dec), 37 (hex)
'8' = 56 (dec), 38 (hex)
'9' = 57 (dec), 39 (hex)