使用CharBuffer.toString()時, 要注意, 輸出的字串, 是從指標所在的位置開始寫的, 因此, 在輸出之前, 要加上: position(0), 如:
以下是一個範例, 將32位元有正負的整數, 傳成十六進位數字,
/**
* Convert 32 bits integer number to hex-decimal string
* @param num number to convert
* @return hex-decimal string
*/
public static String Int32ToHex(int num) {
final int BUFFER_SIZE=8;
final int BITS=32;
String pattern="0123456789ABCDEF";
CharBuffer digits=CharBuffer.allocate(BUFFER_SIZE);
int digit=0;
int ref=0x80000000;
int bitValue=0x8;
for(int i=0;i<BITS;++i) {
int offset=i%4;
if(offset==0 && i!=0) {
digits.append(pattern.charAt(digit));
digit=0;
bitValue=0x8;
}
if((num & ref)!=0) digit += bitValue;
bitValue >>= 1;
/***
* Notice that,
* 0x80000000(-2147483648) >> 1 is NOT 0x40000000, but 0xC0000000(-1073741824)
* (-->E0000000(536870912)-->F0000000(268435456)-->F8000000(-134217728))
* Always divide by 2, no matter positive or negative number
* and 0xFFFFFFFF(-1) >> 1 is NOT 0x7FFFFFFF, but still 0xFFFFFFFF
* For the positive integer, the bit operation is running just as expectation.
*/ if(ref==0x80000000) ref=0x40000000;
else ref >>= 1;
}
digits.append(pattern.charAt(digit));
digits.position(0);
return digits.toString();
}
沒有留言:
張貼留言