Unis
Unis

Reputation: 377

Convert Bytes to short or integer

I do have the following code that read in from a socket:

Int8     buffer[102400];
UInt8     *buffer_p = buffer;;
int       bytesRead;
bytesRead = CFReadStreamRead(stream, buffer, 102400); 

The message i am expecting begin with short(2 bytes) short(2 bytes) integer(4 bytes). I am not sure how to convert them to the corresponding types.

I tried the following:

uint16_t zero16 = NTOHS(buffer_p);
buffer_p += sizeof(uint16_t);
uint16_t msg_id16 = NTOHS(buffer_p);
buffer_p += sizeof(uint16_t);
uint32_t length32 = NTOHL(buffer_p);
buffer_p += sizeof(uint32_t);

or

NSMutableData *data = [NSMutableData dataWithBytes:buffer length:bytesRead];

NSRange firstshort = {0,2};
NSRange secondshort = {2,2};
NSRange intrange = {4,4};
short zero;
[data getBytes:&zero range:firstshort];
short msgid;
[data getBytes:&msgid range:secondshort];
int length;
[data getBytes:&length range:intrange];

But non is working. Thanks in advance.

Upvotes: 3

Views: 3420

Answers (1)

Lily Ballard
Lily Ballard

Reputation: 185681

You may want to look at OSByteOrder.h. This defines a bunch of macros that can be used to read various integer types or to do byte-swapping. Specifically, you could do something like

uint16_t zero16 = OSReadBigInt16(buffer_p, 0);
uint16_t msg_id16 = OSReadBigInt16(buffer_p, 2);
uint32_t length32 = OSReadBigInt32(buffer_p, 4);

Upvotes: 9

Related Questions