Question: Please help! I have to write a program to convert hexadecimal, binary, decimal, and two's complement!?


( Back )

Answer #1:

You can take the input as a string. Then you get the lenght of the array. Say it is n. Then the Most significant bit at position (n-1). So starting from that location you can compute something like this:

dec = 0;
pow = 1;
for (int i = 0;i < len;i++)
{
dec += (input[i]-'0') * pow;
pow <<= 1;
}

left shift is calculating the 2^i for i-th position. So it is calculating:

a(n-1)*2^(n-1) + a(n-2)^2^(n-2) + ... + a0

where ai is the i-th bit.

For hexadecimal thing what you need to do is check each 4 bits from right to left and convert it to corresponding hex digit. eg
1111 1111 1111 1111 would be 0xFFFF
you can do something like this:

char to_hex[] = {0, 1, 2, 3, ..., F}
int k = 0;
for (i = 0;i < len;i+=4)
{
char temp[5];
temp[0] = input[i-3];
temp[1] = input[i-2];
temp[2] = input[i-1];
temp[3] = input[i];
int d = the_function_defined_above_to_convert_to_decimal(temp);
output[k++] = to_hex[d];
}

before you use the hexadecimal converted you have to make sure that the length corresponds to a multiple of 4. You can do this by inserting zeros before the input array.





** Powered by Yahoo Answers