user3703112
user3703112

Reputation: 55

Convert 12bit to decimal

I would like to convert 12bit to decimal number in C language.

for example if we have:

A1=0x5D A2=0xA0 (LSB bits in A2 always is 0)

so if we put these together we have:

0x5DA and it is equal to 1498.

could you please guide me how can I do this in C ?

Upvotes: 2

Views: 2245

Answers (3)

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70931

You can do this relatively easy in C:

val = ((A1 << 8) + A2) >> 4;

You simply concatenate the two numbers and after that remove the last 4 bits that are always zero.

Upvotes: 0

Sebastian Mach
Sebastian Mach

Reputation: 39089

It depends on your definition of converting it to a decimal number.

When you do ...

int A1 = 0x5D;
int A2 = 0xA0;
int B  = (A1 << 4) | (A2 >> 4); // (*)

... then B can be used as-if decimal, even though its representation is or may be binary:

printf("%d", B);

The statement int B = (A1 << 4) | (A2 >> 4); can be explained as follows:

  • << is left shift, bits will be shifted out, zeroes will fill up
  • >> is right shift, bits will be shifted out, zeroes will fill up
  • X << Y means shift X to the left by Y binary digits
  • | combines both operands using bitwise or

In summary: Shifting A1 by 4 bits to the left introduces four zeros on the least significant side. You then fill it up with A2 "minus" its four least significant bits.

Upvotes: 3

SleuthEye
SleuthEye

Reputation: 14579

A1 needs to be shifted 4 bits to the left to make room for the bits of A2, which can be done with A1 << 4.

Then A2 needs to be shifted 4 bits to the right to get rid of the extra zeros in the least-significant bits, which can be done with A2>>4.

Then the two parts could be combined with | operator:

(A1 << 4) | (A2 >> 4);

Upvotes: 5

Related Questions