简体   繁体   中英

Why does this mathematical operation work? (Getting 8-bit register from 32-bit register)

E?X % 256 = ?L

That always seems to work where 256 is in base 10 and % is the modulus function.

Why?

"mod 256" is the remainder after division by 256.

In binary, this turns out to be the lowest 8 bits (because 256 is 2 to the 8th).

This is just like "mod 2" gives you the least significant bit (0 or 1).

On (in decimal, base 10), "mod 100" gives you the last two decimals ( 2013 mod 100 => 13).

It's just the way math works. If you divide a number x by m n , the remainder will be the least significant n digits of x in base m .

For example, in base 10, if you divide any number by 10 n , the remainder of the division will be the least significant n digits of your original number. Examples:

     5 mod 10^1 =    5 mod 10  =  5
  1245 mod 10^2 = 1245 mod 100 = 45

Exactly the same thing happens in binary - 256 is 2 8 (or 100000000 in binary, if you prefer). If you divide any number by 100000000 the remainder will be the least significant 8 bits of the that number.

Simple : When you take mod by 256 you are actually taking mod by 100000000

For example : Suppose you have the 32-bit number 11110011111111001111011011110000 and divide it by 256 (base 10) / 100000000 so you are basically taking out the last 8 bits of the number ie 11110000 , you can think of it in this way . In decimal suppose you want a last 4 digits so you have to take mod by 10000 (base 10) . Similar is the case with binary numbers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM