1

I'am actually reading the interoperability tutorial in Erlang C and Erlang: Erlang Port example i want to know how the c program works:

The function read_exact(byte *buf, int len) reads exactly len Bytes from stdin and puts them in buf, but i don't undrestand what read_cmd do

read_cmd(byte *buf)
{
 int len;

 if (read_exact(buf, 2) != 2)
 return(-1);
 len = (buf[0] << 8) | buf[1];
 return read_exact(buf, len);
} 

especially this line

len = (buf[0] << 8) | buf[1];

let's take an example: if we run the program and put 12 in the input 12 is coded in ASCII so buf[0]=0x31 and buf[1]=0x32 then len =0x3132 which is equal 12549 in decimal then we pass len to read_exact, that means that we have to read 12549 bytes. Does that make a sense?

Community
  • 1
  • 1
Bou6
  • 84
  • 2
  • 10

1 Answers1

0

It reads a "packet" from a byte stream, where the "packet length" is 16 bits (assuming 8-bit chars), stuffing the bytes read into a buffer (that has to be large enough to accommodate the read bytes) and returns the number of bytes actually read.

First, we read two bytes from the stream (and store them in buf[0] and buf[1]).

Then, len = (buf[0] << 8) | buf[1] (as happens, exactly the same as len = buf[0] * 256 + buf[1]; due to a left-shift by 8 being the same as multiplying by 256, leaving the bottom 8 bits as 0, whereby bitwise or and addition accomplish the same thing) takes the two-byte length prefix and turns it into a single number.

This is then passed in as the number of bytes to read (and stuff into buf).

Vatine
  • 20,782
  • 4
  • 54
  • 70
  • Thanks Vatine , but i think that reading the byte stream and stuffing it in a buffer is done by the function read_exact ,i really don't undresatand what does the variable len do in the function read_cmd – Bou6 May 06 '15 at 17:40
  • @fedi I tried to explain it a bit more fully, better? – Vatine May 08 '15 at 12:13
  • thank you it's clear now. do you know any tool that helps us visualise the data flow between the two modules? – Bou6 May 10 '15 at 09:25