I am trying to convert a binary array to decimal Here is what i have to convert, binTodec[8] = {1,1,1,1,0,0,1,1}
I have started with for(int i=0; i<8; i++)
Is there anybody that can help me
I am trying to convert a binary array to decimal Here is what i have to convert, binTodec[8] = {1,1,1,1,0,0,1,1}
I have started with for(int i=0; i<8; i++)
Is there anybody that can help me
One method is to calculate from the most significant bit to the least significant bit.
If binTodec[0] is the most significant bit in binary number :
The decimal number is
1 * 2^7 + 1 * 2^6 + 1 * 2^5 + 1 * 2^4 + 0 * 2^3 + 0 * 2^2 + 1 * 2^1 + 1 * 2^0
= 243
The implemented code would be
int binTodec[8] = {1,1,1,1,0,0,1,1};
int result = 0;
for (int i = 0; i < 8; i++) {
result *= 2;
result += binTodec[i];
}
printf("%d\n", result);
On the other hand, if binTodec[0] is the least significant bit in binary number :
The decimal number is
1 * 2^0 + 1 * 2^1 + 1 * 2^2 + 1 * 2^3 + 0 * 2^4 + 0 * 2^5 + 1 * 2^6 + 1 * 2^7
= 207
The implemented code would be
int binTodec[8] = {1,1,1,1,0,0,1,1};
int result = 0;
for (int i = 7; i >= 0; i--) {
result *= 2;
result += binTodec[i];
}
printf("%d\n", result);
for (int i = 8; i --> 0;) { ... }for (int i = 7; i >= 0; i--), and add the downto example at the end as additional footnote?--> is not a problem. But calling is an operator confuses people. Beginners might believe that it actually is an operator. Which it is not. It is just a post decrement operator followed by a larger than operator