Saturday, 15 May 2010

c - Convert binary string with leading zeros to hexadecimal string -



c - Convert binary string with leading zeros to hexadecimal string -

i going read codes(binary) text file have info "000101" or "100010". concatenating 2 bits binary strings further. having problem leading zeros,which cant skip. have been trying first converting binary string int (using atoi()) , hexadecimal string. leading zeros if utilize function,it truncates leading zeros. have searched here solutions given not in c language. there direct method or have maintain track of everything? in advance. here function takes int input , converts hexadecimal string

void tohex(int n, char str[]) /* function convert binary hexadecimal. */ { int i=0,decimal=0, rem; char temp[2]; while (n!=0) { decimal += (n%10)*pow(2,i); n/=10; ++i; } /* @ point, variable decimal contains binary number in decimal format. */ i=0; while (decimal!=0) { rem=decimal%16; switch(rem) { case 10: str[i]='a'; break; case 11: str[i]='b'; break; case 12: str[i]='c'; break; case 13: str[i]='d'; break; case 14: str[i]='e'; break; case 15: str[i]='f'; break; default: str[i]=rem+'0'; break; } ++i; decimal/=16; } str[i]='\0'; strrev(str); // function reverse string. if(strlen(str)==1) { temp[0] = '0'; temp[1] = str[0]; temp[2] = '\0'; strcpy(str,temp); } else if(strlen(str)==0) { temp[0] = '0'; temp[1] = '0'; temp[2] = '\0'; strcpy(str,temp); } }

get number of binary digits (before calling atoi)

size_t binlen = strlen(input);

get number of hex digits output (it's binlen/4 rounded up)

size_t hexlen = ((binlen % 4 ? binlen+4 : binlen) / 4);

print integer hex, right number of leading zeroes

sprintf(str, "%0.*x", hexlen, n);

nb. should pass length of output buffer, , utilize snprintf instead ...

c

No comments:

Post a Comment