android十进制转十六进制算法,十进制转十六进制 代码

5621转换为16进制数的方法是“除16取余”方法,

5621/16=商351余5,16进制最后一位为5

351/16=商21余15,16进制右边第二位为F

21/16=商1余5,16进制右边第三位为5

1/16=商0余1,16进制数右边第四为为1

商0就不继续除了最后的结果为15F5#include

#include

using namespace std;

// 整数转换成字符串

string int2str( int num);

int main(int argc, char* argv[])

{

// 十进制转十六进制

int num = 0;

cout<

cin>>num;

string str_num;

while(num / 16 != 0)

{

int a = num / 16;

int mod_a = num % 16;

cout<

string s;

switch(mod_a)

{

case 10:

s = 'A';

break;

case 11:

s = 'B';

break;

case 12:

s = 'C';

break;

case 13:

s = 'D';

break;

case 14:

s = 'E';

break;

case 15:

s = 'F';

break;

default:

s = int2str(mod_a);

break;

}

str_num = s + str_num;

num = a;

}

if(num % 16 != 0)

{

int last_a = num % 16;

str_num = int2str(last_a) + str_num;

}

cout<

return 0;

}

string int2str( int num)

{

if (num == 0 )

return " 0 " ;

string str = "" ;

int num_ = num > 0 ? num : - 1 * num;

while (num_)

{

str = ( char )(num_ % 10 + 48 ) + str;

num_ /= 10 ;

}

if (num < 0 )

str = " - " + str;

return str;

}

你可能感兴趣的:(android十进制转十六进制算法,十进制转十六进制 代码)