How to convert a binary number to a two-digit decimal number in C
I need to convert a binary number to a two-digit decimal number. For example:
01111 becomes 15
00011 becomes 03
I'm not simply trying to display the digits. I need to put each digit into an int v开发者_运维百科ariable. Say I have two int variables, leftnum and rightnum.
Then in the first example, leftnum = 1 and rightnum = 5. In the second example, leftnum = 0 and rightnum = 3.
There are two restrictions which make this a little difficult. mod and / can only be used with powers of 2.
int i = 0;
do {
i ++;
} while (i * 10 <= originalInt);
int leftInt = i - 1; // e.g. for "originalInt = 40" -> "i = 5", so we must decrement 1
int rightInt = originalInt - leftInt * 10;
or more compact and using less variables:
int leftInt = 0;
do {leftInt ++;} while (leftInt * 10 <= originalInt);
int rightInt = originalInt - (-- leftInt) * 10;
#include <stdio.h>
int main()
{
int i = 23;
int left, right;
right = i;
left = 0;
while(right > 9) {
right -= 10;
left += 1;
}
printf("%d %d\n", left, right);
}
or
#include <stdio.h>
int main()
{
int i, left, right;
for(i = 0; i < 100; i++) {
left = ((i+1)*51) / 512;
right = i - (left*10);
printf("%d %d %d\n", i, left, right);
}
}
This is the general procedure in English:
Convert the number to decimal i.e. the int type of C (if bitstring is represented by string) else skip this step.
Use sprintf to obtain the decimal representation of int.
You can pick each character from the string and store the corresponding number accordingly to the require int.
精彩评论