14 Mar 2011, 04:09
John_pragsmall

Lee (1 post)

Hi,all. I love Erlang and I am reading Programming Erlang.I have some questions about the code on page 81.

1> Red=2.
2
2> Green=61.
61
3> Blue=20.
20
4> Mem= <<Red:5, Green:6, Blue:5>>.
<<23,180>>

Why does it print “« 23,180 »”? How does the number (23 and 180) come from?

15 Apr 2012, 17:14
Generic-user-small

Pierre Rouleau (1 post)

The resulting memory area is a 16 bit value consisting of the following 3 groups of bits:

  • 00010 : (5 bits for the number 2)
  • 111101 : (6 bits for the number 61, which is 16#3d or if you prefer 0x3d in C)
  • 10100 : (5 bits for the number 20, which is 16#14, or 0x14 in C)

So you end up with: 00010.111101.10100

  • which is the same as the following (moving the dots): 0001.0111.1011.0100
  • which is, expressed in hexadecimal: 16#17B4
  • If you split each 8-bit word, you get 16#17 followed by 16#B4
  • 16#17 is 23 decimal, and 16#B4 is 180

So, in the end, the «20,180» notation means that the binary value is two bytes, expressed in base-10 numbers: 23 and 180.

24 Jun 2012, 01:37
Generic-user-small

Shailen Karur (3 posts)

Well explained! (Since we are interested in decimal values in bytes, we could omit the conversion to hex, jumping directly to bytes, though that may sometimes come in useful!, thanks Pierre!)

  You must be logged in to comment