Jerome James
Jerome James

Reputation: 11

How to read from char buffer into unsigned long and short

Edit: I am not sure if this code does what I think it does. Could someone tell me how to test it? I.e. what should the buffer in my main function look like? I am assuming that a buffer has data of two fields in the following order type(16 bits), length(32 bits). I'm assuming that the buffer is read in from a file and each of the fields is separated by a space. The fields are stored in network byte order and when I read them I have to convert them back to host byte order.

I'm expecting that the code will read the contents from the file (which should be in network byte order) and display the contents in host byte order. I'm a bit confused about type conversions and what the network byte order will be inside of a file, so I don't know what values to use to test it. Also, I'm not sure if my code is written correctly, could someone who does this sort of thing or knows a bit more about such conversions tell me if my code is correct?

Here's the code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void printRecords(char *buffer)
{
     unsigned int recordType;
     unsigned long recordLength;
     char *data;
     char *index;

     if (!buffer)
         printf("Empty buffer\n");

     while(*buffer)
     {
        memcpy(&recordType,(const void *) buffer,2);
        buffer += 3;

        recordType = ntohs(recordType);
        printf("Record type normal: %u\n",recordType);

        memcpy(&recordLength,(const void *) buffer,4);
        buffer += 5;
        recordLength = ntohl(recordLength);
        printf("Record Length normal: %l\n",recordLength);

        break;
     }
}

void main()
{
     char * buffer = "0000000000000001 00000000000000000000000000000001";
     printRecords(buffer);

}

Upvotes: 1

Views: 1351

Answers (1)

loreb
loreb

Reputation: 1357

char *buffer = malloc(sizeof(buf));

sizeof means "size of buf's type", ie the size of a pointer to char; you probably want

malloc(strlen(buf) + 1); /* 1 for trailing '\0' */

Then you are mistaking the value of the bytes for their conversion to string: "256" is byte '2' followed by byte '5' and '6' -- '2' is not equals to 2, '5' is not equals to 5 etc. The 256 you are talking about is 00000001 00000000 instead (try dumping the bytes to stdout and you'll see).

Also, recordType should be of type uint16_t, not unsigned -- you're never too paranoid.

EDIT: atoi takes a pointer to char, as in

atoi("123")

not a pointer to int!

Upvotes: 2

Related Questions