如何将十六进制转换为、二进制、八进制、十进制
2016-04-24 15:10
459 查看
1.十六进制 –> 二进制
这个和二进制转十六进制的思想是一样的。
2.十六进制 –> 八进制
注意:最大支持12位的16进制
3.十六进制转换为十进制
直接求权值和即可
void HexToBin(char* hex, char* bin, int n = 20) { char a[17][6] = { "0000 ","0001 ","0010 ","0011 ", "0100 ","0101 ","0110 ","0111 ", "1000 ","1001 ","1010 ","1011 ", "1100 ","1101 ","1110 " ,"1111 " }; int* temp = (int*)malloc(sizeof(int)*n); memset(temp, 0, n * 4); char* h = hex; int i = 0, j = 0, k = 0, g = 0; while (*h) //把十六进制的每一位转换为整数 { char ch = *h; if (ch == 'A')temp[i++] = 10; else if (ch == 'B') temp[i++] = 11; else if (ch == 'C') temp[i++] = 12; else if (ch == 'D') temp[i++] = 13; else if (ch == 'E') temp[i++] = 14; else if (ch == 'F') temp[i++] = 15; else temp[i++] = *h - '0'; h++; } do { while (j < 5) bin[k++] = a[temp[g] % 16][j++]; j = 0; } while (i>++g); free(temp); }
这个和二进制转十六进制的思想是一样的。
2.十六进制 –> 八进制
long long HexToOct(char* hex) { long long oct = 0; long long dec = 0; char* h = hex; int p = 0, q = 0, i = 0, g = 0; int temp[30] = { 0 }; while (*h++) ++p; //calc hex arrary length h = hex; while (*h) //把十六进制的每一位转换为整数 { char ch = *h; if (ch == 'A')temp[i++] = 10; else if (ch == 'B') temp[i++] = 11; else if (ch == 'C') temp[i++] = 12; else if (ch == 'D') temp[i++] = 13; else if (ch == 'E') temp[i++] = 14; else if (ch == 'F') temp[i++] = 15; else temp[i++] = *h - '0'; h++; } i = 0; while (p) //十六进制 --> 十进制 dec += powl(16, --p)*temp[i++];//因为powl的缘故,十六进制不能太大 memset(temp, 0, sizeof(temp)); i = 0; while (dec) //十进制 --> 八进制 { temp[i++] = (dec % 8); dec = dec >> 3; } while (q < i) oct += powl(10, q++)*temp[g++]; return oct; }
注意:最大支持12位的16进制
3.十六进制转换为十进制
直接求权值和即可
long long HexToDec(char* hex) { long long dec = 0; int temp[30] = { 0 }; char* h = hex; int i = 0, p = 0; while (*h++) ++p; while (*hex) { char ch = *hex; if (ch == 'A')temp[i++] = 10; else if (ch == 'B') temp[i++] = 11; else if (ch == 'C') temp[i++] = 12; else if (ch == 'D') temp[i++] = 13; else if (ch == 'E') temp[i++] = 14; else if (ch == 'F') temp[i++] = 15; else temp[i++] = *hex - '0'; hex++; } i = 0; while (p) dec += powl(16, --p)*temp[i++]; return dec; }
相关文章推荐
- centos安装配置amoeba以及测试
- Jquery easyUI 注意点
- 富文本框KindEditor的使用技巧
- 求逆序数
- 解决方案_北京集体户口离职/辞职/跳槽_集体户口托管/挂靠_2015年9月
- 【bzoj 1467】Pku3243 clever Y
- poj 2431 Expedition
- 分分钟钟搞定二维码生成以及扫描
- 1011 Oil Deposits
- OpenCV3.0配置
- SpringMVC传值中文乱码解决方案
- 过拟合及其解决方法
- [Perl]$SIG{INT}
- Cannot open source file: 'D:\Program Files\Microsoft Visual Studio\VC98\MFC\SRC\APPMODUL.CPP': No s
- 值得推荐的C/C++框架和库
- 第八周进度条
- 使用composer新建一个laravel项目
- 新手学Struts(一)----JSP+Servlet讲解MVC实现原理
- MySQLdb模块中的常用方法
- len