# Getting bit on bytes

**URL:** <https://www.ruby-forum.com/t/getting-bit-on-bytes/108757>\
**Category:** Ruby\
**Created:** [July 6, 2007, 7:38pm UTC](https://www.ruby-forum.com/t/getting-bit-on-bytes/108757 "2007-07-06T19:38:22Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![nephish](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/8e7dd6/32.png) [@nephish](https://www.ruby-forum.com/u/nephish)\
**Post date:** [July 6, 2007, 7:38pm UTC](https://www.ruby-forum.com/t/getting-bit-on-bytes/108757/1 "2007-07-06T19:38:22Z")

</div>

hey there all, i have a question concerning making numbers from bytes  
and back agian

if i have some numbers:  
lo byte = 192  
hi byte = 176  
i can get the number 12480 like this:  
(176 & 127) \* 256 + 192 = 12480

but if i start with the 12480, how do i get the two bytes (lo and hi)  
that make it up?

i kinda know what i am doing here, but keep getting tripped up

thanks

---

<div class="post-metadata">

**Author:** ![nephish](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/8e7dd6/32.png) [@nephish](https://www.ruby-forum.com/u/nephish)\
**Post date:** [July 6, 2007, 7:45pm UTC](https://www.ruby-forum.com/t/getting-bit-on-bytes/108757/2 "2007-07-06T19:45:22Z")

</div>

On Sat, Jul 07, 2007 at 02:37:09AM +0900, shawn bright wrote:

> hey there all, i have a question concerning making numbers from bytes  
> and back agian
> 
> if i have some numbers:  
> lo byte = 192  
> hi byte = 176  
> i can get the number 12480 like this:  
> (176 & 127) \* 256 + 192 = 12480

It’s usually written (176 \<\< 8) + 192, and I don’t know why you want to  
zero out the high bit if you claim that the high byte is the high byte.

> but if i start with the 12480, how do i get the two bytes (lo and hi)  
> that make it up?

hi = 255 & (12480 \>\> 8)  
lo = 255 & 12480

> i kinda know what i am doing here, but keep getting tripped up  
> thanks  
> –Greg

---

<div class="post-metadata">

**Author:** ![nephish](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/8e7dd6/32.png) [@nephish](https://www.ruby-forum.com/u/nephish)\
**Post date:** [July 6, 2007, 8:20pm UTC](https://www.ruby-forum.com/t/getting-bit-on-bytes/108757/3 "2007-07-06T20:20:25Z")

</div>

well, it’s very strange to me too.

you see, we are reading info from sensors through a serial port, as  
the message comes in, i collect all the bytes into an array msg\_list  
the id number of the sensor, i get like this.  
sensor = (msg\_list[1] & 127) \* 256 + msg\_list[0]

so, now my challenge is to write commands back to the sensor so i need  
to take the sensor number that we have in the database and create the  
bytes out of it to write to the port.

i don’t know exactly why the first byte is masked in the msb. I just  
did it because their docs told me to.

thanks
