mardi 4 août 2015

Hex to int conversion of input data using C program

I am trying to convert a hexadecimal data coming from a port( stored in a buffer) into integer format using C program. Before converting from buffer, I wanted to test my code by giving some input in the program. The following is the program I am using from a online source.

#include <stdio.h>
#include <stdlib.h>

int hexToInt(char s[]) {
int hexdigit, i, inhex, n;    
i=0;

if(s[i] == '0') {
    ++i;
    if(s[i] == 'x' || s[i] == 'X'){            
        ++i;
    }
}

n = 0;
inhex = 1;
for(; inhex == 1; ++i) {
    if(s[i] >= '0' && s[i] <= '9') {            
        hexdigit = s[i] - '0';
    } else if(s[i] >= 'a' && s[i] <= 'f') {            
        hexdigit = s[i] - 'a' + 10;
    } else if(s[i] >= 'A' && s[i] <= 'F') {
        hexdigit = s[i] - 'A' + 10;
    } else {
        inhex = 0;
    }

    if(inhex == 1) {
        n = 16 * n + hexdigit;
    }
}

return n;
}

int main(int argc, char** argv) {

char hex[] = "93 BC";
int digit = hexToInt(hex);
printf("The Integer is %d", digit);

return 0;
}

When I run this program it converts one input of Hexadecimal into a integer. But If I had to convert of array of hex input like the below:

00 00 00 05 00 00 00 01 93 BC C0 06 00 00 00 00         ................
00 28 17 00 FC 26 CC 62 00 00 00 07 00 00 00 01         .(...&.b........
00 00 00 D0 00 E3 37 19 00 00 00 1D 00 00 01 00         ......7.........
AB B6 CD 14 00 11 1F 3C 00 00 00 1D 00 00 00 00         .......<........
00 00 00 02 00 00 00 01 00 00 00 90 00 00 00 01         ................
00 00 05 EE 00 00 00 04 00 00 00 80 F0 92 1C 48         ...........�...H
C2 00 00 0E 0C 30 C7 C7 08 00 45 00 05 DC 32 70         .....0....E...2p
40 00 2D 06 41 C8 2D 3A 4A 01 93 BC C8 EC 01 BB         @.-.A.-:J.......
C1 58 C5 8D 53 88 05 72 46 E6 80 10 00 53 DC 34 

Then how I can convert it into corresponding integer values?

Aucun commentaire:

Enregistrer un commentaire