函數(shù)原型: 1 2 3 4 | //轉(zhuǎn)二進(jìn)制
char *ConvertTo2String( long number);
//轉(zhuǎn)十六進(jìn)制
char *ConvertTo16String( long number);
|
思路: 轉(zhuǎn)換二進(jìn)制很簡單,,二步操作即可完成, 1:循環(huán)對數(shù)字1左移31-i(i={0,31})位(從高位開始的),再與把number作位與操作,, 2:再把剛才的結(jié)果通過右移31-i (i={0,31}) 位得出每一位是否為0還是1,, 這樣就得到了每一位的二進(jìn)制位,再把這些二進(jìn)制位拼成字符串就OK了,!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | char *ConvertTo2String( long number)
{
char *output = NULL;
output = ( char *) malloc (33); //include '\0'
int i = 0;
for (;i<32;i++)
{
output[i] = number & (1<<31-i);
output[i] = output[i] >> 31-i;
output[i] = (output[i] == 0) ? '0' : '1' ;
}
output[i] = '\0' ;
return output
}
|
轉(zhuǎn)換十六進(jìn)制麻煩一點(diǎn),,要考慮字母的情況,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | char * ConvertTo16String( long number)
{
char *output= NULL;
char *temp = NULL;
output= ( char *) malloc (11);
output[0] = '0' ;
output[1] = 'x' ;
output[10] = '\0' ;
temp = output+ 2;
for ( int i = 0; i<8; i++)
{
temp[i] = ( char )(number<< 4 * i >> 28); //先左移4*i,,再右移28,每一次處理4位
temp[i] = temp[i]>=0 ? temp[i] : temp[i]+16; //為轉(zhuǎn)換為A~F的字母作準(zhǔn)備
temp[i] = temp[i] < 10 ? temp[i]+48 : temp[i]+55; //轉(zhuǎn)字母
}
return output;
}
|
函數(shù)原型: 1 2 3 4 | //轉(zhuǎn)二進(jìn)制
char *ConvertTo2String( long number);
//轉(zhuǎn)十六進(jìn)制
char *ConvertTo16String( long number);
|
思路: 轉(zhuǎn)換二進(jìn)制很簡單,,二步操作即可完成, 1:循環(huán)對數(shù)字1左移31-i(i={0,31})位(從高位開始的),再與把number作位與操作,, 2:再把剛才的結(jié)果通過右移31-i (i={0,31}) 位得出每一位是否為0還是1,, 這樣就得到了每一位的二進(jìn)制位,再把這些二進(jìn)制位拼成字符串就OK了! 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | char *ConvertTo2String( long number)
{
char *output = NULL;
output = ( char *) malloc (33); //include '\0'
int i = 0;
for (;i<32;i++)
{
output[i] = number & (1<<31-i);
output[i] = output[i] >> 31-i;
output[i] = (output[i] == 0) ? '0' : '1' ;
}
output[i] = '\0' ;
return output
}
|
轉(zhuǎn)換十六進(jìn)制麻煩一點(diǎn),,要考慮字母的情況,, 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | char * ConvertTo16String( long number)
{
char *output= NULL;
char *temp = NULL;
output= ( char *) malloc (11);
output[0] = '0' ;
output[1] = 'x' ;
output[10] = '\0' ;
temp = output+ 2;
for ( int i = 0; i<8; i++)
{
temp[i] = ( char )(number<< 4 * i >> 28); //先左移4*i,再右移28,每一次處理4位
temp[i] = temp[i]>=0 ? temp[i] : temp[i]+16; //為轉(zhuǎn)換為A~F的字母作準(zhǔn)備
temp[i] = temp[i] < 10 ? temp[i]+48 : temp[i]+55; //轉(zhuǎn)字母
}
return output;
}
|
|