Home > Back-end >  how is this arithmetic operation done behind the scene?
how is this arithmetic operation done behind the scene?

Time:10-12

I know every single bit in a byte is assigned to a number like this:

128 64 32 16 8 4 2 1

   0  0  0  0  0  0  0  0

To count this it is very simple by multiplying the input number by the assigned number like this :

if we enter 1 : 0b00000001
result is : 1

if we enter 1 again: 0b00000011
result is : 3

if we enter 1 again: 0b00000111
result is : 7

this is how the first byte is calculated and i understand it very well the problem is when we add another byte it will become 16 bits i know that but how is it gonna be calculated the last number we get from the first byte is 255 how can we continuing the calculation ???

CodePudding user response:

The values of the different binary positions will be powers of 2. Counting from the right you get

20=1, 21=2, 22=4, …

So from one step to the next you multiply by 2.

But your question was different. You were asking about numbers that are all zeros on the left and all ones on the right. Note that if you add 1 to such a number you get carry all the way until you end up with a single 1. So those numbers are one less than powers of 2:

21-1=1, 22-1=3, 23-1=7, …

So to go from one number to the next, one way is to add 1, multiply by 2, then subtract 1. Equivalently you can multiply by 2 (which effectively moves your block of ones one position to the left) then add 1.

CodePudding user response:

to convert binary into decimal you simply take each digit value and multiply it with its position value and sum up them all for example 0b11001010:

position      :   7   6   5   4   3   2   1   0
position_value: 128  64  32  16   8   4   2   1
digit_value:      1   1   0   0   1   0   1   0
-----------------------------------------------
           x =  128  64   0   0   8   0   2   0 = 202

the position values are simply powers of 2:

position_value = 2^position

And can be extended bitwidth in both directions (after decimal point the position are -1,-2,-3,...)

position      : ...    9   8   7   6   5   4   3   2   1   0 ,  -1   -2    -3 ...
position_value: ... 1024 512 128  64  32  16   8   4   2   1 , 0.5 0.25 0.125 ...

so the position_value is always *2 (or /2) of the previous (or next) position_value ...

  • Related