"Golan" <bc****@mot.com> wrote in message
I need to convert a Binary value to Decimal. I've been told that the
value is an unsigned one. How can I do this?
Presumably you mean convert a machine representation value into something
suitable for human reading.
The normal way to do this is
sprintf("%d", (int) x);
if the value is unsigned
sprintf("%u", (unsigned int) x);
However generally unsigned integer values are a BAD THING, use normal int
unless you really do need that extra bit.
I use memcpy into an unsigned char variable, but when I print the
value I got a negative value.
For example if I'm using the xd -c (Unix) on the file, I can see the
value FFFFFFFFFFFFFFA2 which using the memcpy as described
above I get -94.
But the real value that I'd expect to get is a positive one.
OK. It's almost certain that char on your machine is 8 bits. Something is
sign-extending the value to 64 bits. Since your value (0xA2) is greater than
127, a signed char with the same bit pattern would be negative.
memcpy() ing a value into an unsigned char doesn't sound like the way to go.
What is the data originally?
Another problem, I've told you to use sprintf(), but how does sprintf() work
internally? It's something like this.
void bintoascii(char *out, int x)
{
char *save;
char temp;
/* add the minus */
if(x < 0)
{
*out++ = '-';
x = -x;
}
/* handle 0 specially */
if(x == 0)
{
*out++ = '0';
*out = 0;
return;
}
save = out;
while(x)
{
*out++ = (x % 10) + '0';
x /= 10;
}
*out = 0;
out--;
/* reverse the number */
while(out > save)
{
temp = *out;
*out = *save;
*save = temp;
save++;
out--;
}
}