這篇文章主要介紹了C++實(shí)現(xiàn)十六進(jìn)制字符串轉(zhuǎn)換為十進(jìn)制整數(shù)的方法,涉及C++字符串與數(shù)制轉(zhuǎn)換的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
本文實(shí)例講述了C++實(shí)現(xiàn)十六進(jìn)制字符串轉(zhuǎn)換為十進(jìn)制整數(shù)的方法。分享給大家供大家參考。具體實(shí)現(xiàn)方法如下:
- /*
- * 將十六進(jìn)制數(shù)字組成的字符串(包含可選的前綴0x或0X)轉(zhuǎn)換為與之等價(jià)的整型值
- */
- #include <stdio.h>
- #include <math.h>
- /* 將十六進(jìn)制中的字符裝換為對(duì)應(yīng)的整數(shù) */
- int hexchtoi(char hexch )
- {
- char phexch[] = "ABCDEF";
- char qhexch[] = "abcdef";
- int i;
- for(i=0;i<6;i++){
- if((hexch == phexch[i]) || (hexch == qhexch[i]))
- break;
- }
- printf("i=%d",i);
- if(i >= 6){
- return 0; /* 非十六進(jìn)制字符 */
- }
- return 10+i;
- }
- int htoi(char s[])
- {
- int n=0; /*有n位*/
- int valu=1; /*是否有效*/
- int i=0,j;
- int answer=0;
- /* 有效性檢查 */
- if((s[0] == '0') && ((s[1] == 'x') || (s[1] == 'X'))){
- i += 2;
- }
- while((s[i] != '/n')){
- if((s[i] < '0') && (s[i] > '9')){
- if(hexchtoi(s[i]) == 0){
- valu=0;
- break;
- }
- }
- n++;
- i++;
- }
- if(valu != 0){
- for(j=0;j<n;j++){
- answer += ((int)pow(16,j) * hexchtoi(s[i-j-1]));
- }
- }
- else
- answer = -1;
- return answer;
- }
- main()
- {
- char *n[] = {"0x7ff0","0x2341"};
- printf("%s is %d/n",n[0],htoi(n[0]));
- printf("%s is %d/n",n[0],123);
- }
希望本文所述對(duì)大家的C++程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答