简体   繁体   中英

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM