convert a binary into decimal

Q

QQ

Hello

unsigned char a;

the a[0-3] represents a 4-bit binary,
a[4-6] represents another 3-bit binary.

I'd like to convert a[0-3] into a decimal.
For instance if {a[3] a[2] a[1] a[0}}= {0 1 0 1] the decimal should be
5

My program is like

if((a && 0x00)==1) return 0;
else if (a&& 0x01)==1) return 1;
.....

Is there any simpler way for it?

Thanks a lot!
 
P

pemo

QQ said:
Hello

unsigned char a;

the a[0-3] represents a 4-bit binary,
a[4-6] represents another 3-bit binary.

I'd like to convert a[0-3] into a decimal.
For instance if {a[3] a[2] a[1] a[0}}= {0 1 0 1] the decimal should
be 5

My program is like

if((a && 0x00)==1) return 0;
else if (a&& 0x01)==1) return 1;
....

Is there any simpler way for it?

Thanks a lot!

0-3 = a & 0x0F;
4-6 = (a & 0x70) >> 4;
 
M

Martin Ambuhl

QQ said:
unsigned char a;
the a[0-3] represents a 4-bit binary,
a[4-6] represents another 3-bit binary.
I'd like to convert a[0-3] into a decimal.
For instance if {a[3] a[2] a[1] a[0}}= {0 1 0 1] the decimal should be
5

My program is like

if((a && 0x00)==1) return 0;
else if (a&& 0x01)==1) return 1;

I don't understand how the above can do what you want.
Is there any simpler way for it?

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <limits.h>

int main(void)
{
unsigned char a;
int i;
srand(time(0));
for (i = 0; i < 4; i++) {
a = (unsigned) rand();
printf
("a = %3u (%#03o, %#02x), first 4 bits=%u,"
" next 3 bits=%u\n",
a, a, a, a >> (CHAR_BIT - 4), 07 & (a >> (CHAR_BIT - 7)));
}
return 0;
}


a = 186 (0272, 0xba), first 4 bits=11, next 3 bits=5
a = 171 (0253, 0xab), first 4 bits=10, next 3 bits=5
a = 19 (023, 0x13), first 4 bits=1, next 3 bits=1
a = 98 (0142, 0x62), first 4 bits=6, next 3 bits=1
 
B

Barry Schwarz

Hello

unsigned char a;

the a[0-3] represents a 4-bit binary,
a[4-6] represents another 3-bit binary.

I'd like to convert a[0-3] into a decimal.
For instance if {a[3] a[2] a[1] a[0}}= {0 1 0 1] the decimal should be
5

My program is like

if((a && 0x00)==1) return 0;

The if is guaranteed to always be false. Anything && 0 is always
false.
else if (a&& 0x01)==1) return 1;

This is no different than if(a). Did you perhaps mean (a & 0x01)?

Apparently your unsigned char holds 0 or 1 as opposed to '0' and '1'.
In this case, you can compute
num1 = a[3]*8 + a[2]*4 + a[1]*2 + a[0];
and
num2 = a[6]*4 + a[5]*2 + a[4];


Remove del for email
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top