How to convert two bytes to one 16-bit number?

I understand that 1 byte will contain a number from 0 to 255. And this 16-bit number is between 0-65535.

If I try to represent a 16-bit number using two separate 8-bit registers ... how to do this? How does math work?

Thanks!

+6
source share
3 answers

Mathematics works as follows:

sixteenBitNumber = 256*upperByte + lowerByte; 

with shifts and bitwise operations:

 sixteenBitNumber = (upperByte<<8) | lowerByte; 

On most processors, even some archaic 8-bit ones, this interpretation is done on a hardware level: you load bytes in parts of a 16-bit register or in separate 8-bit registers that can work as a 16-bit pair, and the hardware works with data as if it were a single 16-bit number.

+10
source

In decimal form, how can I take 7 and 9 and make 79? (7 * 10) +9 Or 12 and 34 and make 1234? (12 * 100) +34. No other 0x12 and 0x34 and do 0x1234. (0x12 * 0x100) + 0x34. A much cleaner bit offset (0x12 <8) + 0x34. you can or is it also (0x12 <8) | 0x34.

+1
source

Do you want to work with them together? Easy

Let's say you have number 2643 - in base 10 . if you split it in half, you will have something like 26 and 43, right? well, you know that if you multiply by two, you must multiply from right to left and carry. So do it - multiply the right side, and if there is an overflow, add this to the left, and then multiply the left side.

For instance:

 (37 82) *2 -> ((37*2) + overflow) + 64 -> (74 + 1) 64 -> 75 64 

See how it works? The same goes for division - should I wear? Steal from a higher bit. Want to add or subtract numbers? Not so hard after all!

Binary numbers work the same way.

 (01110110 10110011) * 10 = (0) <- 1110110(1) <- 01100110 

Basically you calculate the lower end, then calculate the upper end, then apply overflow.

0
source

Source: https://habr.com/ru/post/917213/


All Articles