How to parse a char array as a whole?

I have a buffer like a char array, like this:

char buf[4]; buf[0] = 0x82; buf[1] = 0x7e; buf[2] = 0x01; buf[3] = 0x00; 

Now, I would like to read char two and three together as an unsigned 16Bit integer in a large endian. How to do this using standard C (++) tools?

Currently, I only know the manual solution:

 int length = but[3]; length += but[2] << 8; 

This would be easy for 16Bit integers, but I would also need to parse 32Bit integers, which would make things a little complicated. So, is there a function from the standard lib library that does this for me?

Bodo

+4
source share
3 answers

You can use ntohs and ntohl (on a small system):

 #include <iostream> #include <cstring> #include <arpa/inet.h> int main(){ char buf[4]; buf[0] = 0x82; buf[1] = 0x7e; buf[2] = 0x01; buf[3] = 0x00; uint16_t raw16; uint32_t raw32; memcpy(&raw16, buf + 2, 2); memcpy(&raw32, buf , 4); uint16_t len16 = ntohs(raw16); uint32_t len32 = ntohl(raw32); std::cout << len16 << std::endl; std::cout << len32 << std::endl; return 0; } 

Or you can swap bytes around and translate it to the appropriate type, rather than to carry.

+6
source

You can use union:

 union conv { char arr[4]; short value16[2]; int value32; }; conv tmp; tmp.arr[0] = buf[0]; tmp.arr[1] = buf[1]; tmp.arr[2] = buf[2]; tmp.arr[3] = buf[3]; 

Or memcpy:

 memcpy(&length, buf, sizeof(length)) 
0
source

atoi . more likely the easiest fix.

 int iResult = atoi(buf); 
-2
source

All Articles