arrays - C code to convert hex to int -
i writing code convert hex entry integer equivalent. 10 , b 11 etc. code acts weirdly, in seg. faults @ random locations , including newline character @ times work. trying debug it, can understand doing wrong here. can take , me here ? lot time.
/* fixed working code interested */
#include <stdio.h> #include <stdlib.h> unsigned int hextoint(const char temp[]) { int i; int answer = 0; int dec; char hexchar[] = "aabbccddeeff" ; ( i=0; temp[i] != '\0'; i++ ) { if ( temp[i] == '\0') { return ; } if (temp[i] == '0' || temp[i] == 'x' || temp[i] == 'x' ) { printf("0"); answer = temp[i]; } // compare each temp[i] contents in hexchar[] int j; int = temp[i]; ( j=0; hexchar[j] != '\0'; j++) { if ( temp[i] == hexchar[j] ) { answer *= 16; answer = answer + 10 + (j/2); // printf("%d\n",answer ); break; } } } return answer; } main() { char *test[] = { "bad", "aabbdd" "0100", "0x1", "0xa", "0x0c0be", "abcdef", "123456", "0x123456", "deadbeef", "zog_c" }; int answer=0; // calculate number of char's. int numberofchars; numberofchars = sizeof test /sizeof test[0]; printf("main():number of chars = %d\n",numberofchars); int i; // go through each character , convert hex integers. ( = 0; i<numberofchars;i++) { // need take first char , go through , convert it. answer = hextoint(test[i]); printf("%d\n",answer ); } }
let's take look.
unsigned int hextoint(const char temp[]) { int i; int answer = 0; char hexchar[] = "aabbccddeeff" ; ( i=0; temp[i] != '\0'; i++ ) { printf("in here"); printf("%c\t",temp[i] ); } return answer; }
this doesn't seem try conversion. should return 0, since answer
never assigned other value. normally, you'd like:
for (i=0; input[i] != '\0'; i++) { answer *= 16; answer += digit_value(input[i]); } return answer;
where digit_value
(obviously enough) returns value of individual digit. 1 way is:
int digit_value(char input) { input = tolower(input); if (input >= '0' && input <= '9') return input - '0'; if (input >= 'a' && input <= 'f') return input - 'a' + 10; return -1; // signal error. }
then, looking @ main
:
main() {
depending on "implicit int" rule poor practice, @ least imo. it's better specify return type.
// calculate number of char's. int numberofchars; numberofchars = sizeof test /sizeof test[0];
this calculates number of strings, not number of char
s.
for ( = 0; i<=numberofchars;i++)
valid subscripts run 0 through number of items - 1, attempts read past end of array (giving undefined behavior).
Comments
Post a Comment