# Code working for Hex, but not for Binary

Discussion in 'C' started by jaggu, Nov 30, 2012.

1. ### jagguNew Member

Joined:
Nov 30, 2012
Messages:
1
0
Trophy Points:
0
Hi,

I have two functions. One converts ascii to hex and the other uses the function and displays the inverted data. I have shown the two functions below

Code:
```/*----------------------*/
/* Convert ASCII to hex */
/*----------------------*/
unsigned int asc2hex(char *str)
{
unsigned int res;
char *p;

res = 0;
for (p = str; *p != '\0' ; ++p)
{
res <<= 4;
if (*p >= '0' && *p <= '9')
res |= *p - '0';
else
res |= *p - 'A' + 10;
}
return res;
}```
Code:
```/*----------------------*/
/* Invert data          */
/*----------------------*/
invdata( int cycle, char *actstr, char * userData)
{
char this_input_data[1024];
unsigned int val;

get_facvalue(userData, cycle, this_input_data);
val = asc2hex(this_input_data);
sprintf(actstr,"%08u",~val);
return 0;
}
```
The above functions work perfectly well. But, when I try to do the same and display the result in binary I don't get the proper result. The result just shows "b". I have shown the two functions below

Code:
```/*----------------------*/
/* Convert ascii to binary*/
/*----------------------*/
unsigned int asc2bin(char *str)
{
unsigned int res;
unsigned int binres;
char *p;

binres = 0;
for (p = str; *p != '\0' ; ++p)
{
if (*p >= '0' && *p <= '9')
res = *p - '0';
else
res = *p - 'A' + 10;
binres <<= 4;
switch(res)
{
case '0': binres|='0000';break;
case '1': binres|='0001';break;
case '2': binres|='0010';break;
case '3': binres|='0011';break;
case '4': binres|='0100';break;
case '5': binres|='0101';break;
case '6': binres|='0110';break;
case '7': binres|='0111';break;
case '8': binres|='1000';break;
case '9': binres|='1001';break;
case 'A': binres|='1010';break;
case 'B': binres|='1011';break;
case 'C': binres|='1100';break;
case 'D': binres|='1101';break;
case 'E': binres|='1110';break;
case 'F': binres|='1111';break;
case 'a': binres|='1010';break;
case 'b': binres|='1011';break;
case 'c': binres|='1100';break;
case 'd': binres|='1101';break;
case 'e': binres|='1110';break;
case 'f': binres|='1111';break;
default:break;
}
}
return binres;
}```
Code:
```/*----------------------*/
/* Invert data          */
/*----------------------*/
invdata( int cycle, char *actstr, char * userData)
{
char this_input_data[1024];
unsigned int val;

get_facvalue(userData, cycle, this_input_data);
val = asc2bin(this_input_data);
sprintf(actstr,"%032b",~val);
return 0;
}```
Can you tell me what is wrong?

Thanks!

Joined:
Apr 13, 2012
Messages:
44