# How does this code work, can somebody explain?

Status
Not open for further replies.

#### internetuser2k12

##### Banned Hello!

I want to know how this BCD to Decimal code works.

Code:
 ((bcd >> 4)*10+(bcd & 0x0F));
Should I have to give 0x99 for year 99 for bcd in the formula to get 153 decimal

i.e., (bcd >> 4) = 0x99 >> 4 = 0x09 or d9
(bcd >> 4)*10 = 0x09 * d10 = 0x90 or d144
(bcd & 0x0F) = 0x99 & 0F = 0x09 or d9
finally 0x90 + 0x09 = 0x99 or d144 + d9 = d153.

I have confusion here (bcd >> 4)*10 = 0x09 * d10 = 0x90 or d144 does it calculate 0x90 * d10 or 0x90 * 0x0A? I think it calulates 0x90 * d10 because 10 is written as 10 and not 0x10 or 0x0A. Am I right?

#### FvM

##### Super Moderator
Staff member #### internetuser2k12

##### Banned It is giving 153 decimal for bcd 0x99.

#### Tahmid i.e., (bcd >> 4) = 0x99 >> 4 = 0x09 or d9
(bcd >> 4)*10 = 0x09 * d10 = 0x90 or d144
0x09 * d10 = d90

Code:
(bcd & 0x0F)
If you AND 99 with 0x0F, you get 0x09.

90+9 = 99

That's it. 0x99 "became"/got converted to d99.

#### internetuser2k12

##### Banned No it converts to decimal 153 for bcd 0x99

----------Update--------------

bcd = 0x99

(bcd >> 4) = 0x99 >> 4 = 9

(bcd >> 4)*10 = 9 * 10 = 90

(bcd & 0x0F) = 0x99 & 0x0F = 0x09

(bcd >> 4)*10+(bcd & 0x0F) = 90 + 9 = 99

Am I right now?

Last edited:

#### Tahmid It is giving 153 decimal for bcd 0x99.
It gives decimal 99 for bcd 0x99.

#### FvM

##### Super Moderator
Staff member I mean, use the pocket calculator to trace the operation of the rather straightforward bcd2dec() code.

I really don't understand where you expect to get "decimal 153". After some discussions, we all know the the RTC register content for year 99 is "1001 1001" binary or 0x99 or 153 decimal. Now you're converting it to decimal. We expect an output of 99 decimal, or 0x63, or "0110 0011" binary, isn't it?

• tpetar

### tpetar

points: 2

#### internetuser2k12

##### Banned @ FvM I updated my last post, please check it.

- - - Updated - - -

@ Tahmid. Yes You are right. See my last post. Is the calculation correct?

#### Tahmid No it converts to decimal 153 for bcd 0x99

----------Update--------------

bcd = 0x99

(bcd >> 4) = 0x99 >> 4 = 9

(bcd >> 4)*10 = 9 * 10 = 90

(bcd & 0x0F) = 0x99 & 0x0F = 0x09

(bcd >> 4)*10+(bcd & 0x0F) = 90 + 9 = 99

Am I right now?
Yes, that's correct.

Status
Not open for further replies.