tags:

views:

125

answers:

3

Could someone explain what this code does

size = *(int *)data;        // size of string plus header word
off = (size + 3) & ~3;
chan = *(int *)(data + off);
data[size] = '\0';      // zero terminate

I think it's got something to do with making the data a multiple of 4?

+3  A: 

Assuming that data is a char*...

size = *(int *)data;        // size of string plus header word

data is interpreted as a pointer-to-int, then dereferenced and assigned to size.

off = (size + 3) & ~3;

This rounds size upwards to the nearest multiple of 4, and assigns to off.

chan = *(int *)(data + off);

The value for chan apparently resides off bytes from data.

data[size] = '\0';      // zero terminate

That one is obvious.

Thomas
Thanks Thomas, thats great
mikip
+1  A: 

This line casts data to a pointer to an int and dereferences the pointer and stores the value in an variable named size:

size = *(int *)data;  

This line gets the smallest multiple of four greater than or equal to size and assigns the result to the variable off:

off = (size + 3) & ~3;

This line gets an int value offset sizeof(char) * off bytes from the pointer data and stores the result in chan:

chan = *(int *)(data + off);

This line null-terminates the block of memory:

data[size] = '\0';

So it looks like size is a block of memory wherein the first sizeof(int) bytes of data can be thought of as an int indicating the size of the block of memory. Apparently there is meaningful data at data plus sizeof(char) * smallestmultipleoffourlargerthan(size). Without knowing details of data this is the best we can say.

Jason
Thanks Jason, you have been most helpful
mikip
A: 

Building on Jason's answer, it looks like this code is pulling apart the contents of a data structure whose beginning is stored at data. The data structure that is stored there seems to be formatted something like this:

{
  int size;
  char data[(size + 3) & ~3];
  int chan;
}
Scott W