--- In [email protected], Sanil P S <[EMAIL PROTECTED]> wrote:
>
> Hello.
> Thank you all for the replies.
> I decided to create my own libraries
> to parse and interpret the incoming 
> byte array.
> 
> Thank you
> Sani
> --- Nico Heinze <[EMAIL PROTECTED]> wrote:
> 
> > --- In [email protected], Sanil P S
> > <sanilps@> wrote:
> > >
> > > atoi will not work here.
> > > 
> > > atoi just converts the string to integer.
> > > ie; 4 bytes string like "1234" = 1234
> > > 
> > > check the ASCII values for 1, 2 ,3 and 4 
> > > whcih are 49,50,51,52 corresponding hex values
> > > are 31,32,22,34
> > > 
> > > Binary representation of this is 
> > > 
> > > 0011 0001  0011 0010  0011 0011  0011 0100 ==>Hex 
> >  
> > > 31 32 33 34 ==> decimal 825373492
> > > 
> > > I want to get 
> > > 
> > > Binary ===> Hex ===> decimal
> > > 
> > > 00000001 00000001 0000001 00010000 ==>01 01 01 10
> > > ==>16843024
> > > 
> > > 00000001 00000001 0000001 00011110 ==>01 01 01 1E
> > > ==>16843038
> > <snip>
> > 
> > In this case it does make sense to read() (or
> > recv(), for that matter)
> > the four bytes as char*; however, processing goes on
> > like this:
> >   /* Check that four bytes can be read: */
> >   if (read( ifd, chararr, sizeof( chararr)) != 4)
> >   { perror( "Couldn't read 4 length bytes");
> >     exit( EXIT_FAILURE);
> >   }
> >   /* else */
> >   /* Concatenate them into one long value: */
> >   longvalue = ( ( (unsigned long) (chararr [0])) <<
> > 24) +
> >         ( ( (unsigned long) (chararr [1])) << 16) +
> >         ( ( (unsigned long) (chararr [1])) << 8) +
> >         ( (unsigned long) (chararr [1]));

In fact I use this same technique to interpret a highly complex binary
packed byte stream delivered by some application over TCP/IP; I mix up
treatments like the above with strcpy() and the like whenever appropriate.

BTW The most important lesson I've learned while implementing this was
something not directly related to your question: I have written a
small function which returns one single byte from the input stream (I
buffer the input data myself). This function returns an int, not a
char, namely either a value in the range 0 - 255 if the next byte
could be read or -1 to indicate that some error has occurred; this way
it's ugly easy to distinguish between read errors and all legal
values. [Yes, can be done more elegantly, but it works fine and is fast.]

Regards,
Nico

Reply via email to