相关文章推荐
return toUnsignedString0(i, 4); private static String toUnsignedString0(int val, int shift) { // assert shift > 0 && shift <=5 : "Illegal shift value"; //计算这个int转换成二进制后占多少bit(123-->>7) int mag = Integer.SIZE - Integer.numberOfLeadingZeros(val); //用于确定最后生成的字符串有几个字符 int chars = Math.max(((mag + (shift - 1)) / shift), 1); char[] buf = new char[chars]; //具体解析出每个字符是什么 formatUnsignedInt(val, shift, buf, 0, chars); // Use special constructor which takes over "buf". return new String(buf, true); static int formatUnsignedInt(int val, int shift, char[] buf, int offset, int len) { int charPos = len; int radix = 1 << shift;//2^shift (此例子是2^4) int mask = radix - 1; //(16进制-->>15 8进制-->>7) //val&mask 相当于 val%(mask+1) 这里是 123%16 buf[offset + --charPos] = Integer.digits[val & mask]; val >>>= shift; } while (val != 0 && charPos > 0); return charPos;
public class IntegerToHexStringDemo {
	public static void main(String[] args) {
	    byte a=-1;
	    System.out.println("-1 hex  : 0x"+Integer.toHexString(a));
        System.out.println("-1&0xff : 0x"+Integer.toHexString(a&0xff));
		System.out.println("十进制转十六进制:"+Integer.toHexString(120));
-1 hex  : 0xffffffff
-1&0xff : 0xff
十进制转十六进制:78
            

版权声明:本文为JAVASCHOOL原创文章,未经本站允许不得转载。

 
推荐文章