//1:“zyh_helen”+ 1
//2: *“zyh_helen”
//3:“zyh_helen”[2]。
void int_to_hex1(unsigned int n)
{
char array[8];
int count = 0;
while (n)
{
array[count++] = n % 16;
n >>= 4;
}
for (int i = count - 1; i >= 0; --i)
{
if (array[i] <= 9)
printf("%d", array[i]);
else
cout << array[i]-10+'A';
}
cout << endl;
}
方式二:
void int_to_hex3(unsigned int n)
{
char array[8];//32位二進制--->8位16進制(最多需要)
int count = 0;
while (n)
{
array[count++] = "0123456789ABCDEF"[n % 16];
n >>= 4;
}
for (int i = count - 1; i >= 0; --i)
{
cout << array[i];
}
cout << endl;
}
顯然方式一得代碼比較複雜,因爲字母和數字在字符集中並不是相鄰的,方式二定義了一個字符串,使子母和數字相鄰,從而避免了這種複雜性,餘數將在字符串中選擇一個正確的數字。int count(int num)
{
int count = 0;
while (num)
{
count += "\0\1\1\2\1\2\2\3\1\2\2\3\2\3\3\4"[num % 16];
num >>= 4;
}
return count;
}
每次取num的後四位,判斷有多少個1(4位表示的數值:0--15,0到15,二進制中1的個數分別爲0 1 1 2 1 2 2 3 1 2 2 3 2 3 3 4
)‘\’的作用:轉移字符,將字符轉化爲數字