Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting int array to char*

Tags:

c++

Is this possible? I wanted to convert this into a char* so I could later retrieve this values.

like image 238
seed Avatar asked Apr 22 '10 03:04

seed


1 Answers

Sure:

int array[4] = {1, 2, 3, 4};
char* c = reinterpret_cast<char*>(array);

The valid range is from c to c + sizeof(array). You are allowed to do this to any POD type.

You can cast back from a sequence of bytes:

// assuming c above
int (&pArray)[4] = *reinterpret_cast<int(*)[4]>(c);

This is guaranteed to work. But, it seems you're trying to send stuff across a network, which can introduce other problems


The process you're looking for is called serialization (and has a FAQ entry). This is when you take an object, transform it into a series of bits, which can later be "deserialized" into the original object.

Making this work across multiple platforms can be tricky, because you need to make sure you serialize into a specific format, and that each platform knows how it should read from that format. (For example, a big-endian platform might always convert to little-endian before sending, and likewise convert back to big-endian when receiving.) You cannot treat non-POD types as a stream of bytes (such as std::string), so you need to write serialization functions for those, to transform their data into a stream of bytes, and deserialization functions to transform it back.

I particularly like that way Boost does this, and if you can I'd use their serialization library. They basically first define routines for serializing fundamental types, then you can serialize more complex types by building off that. Of course, Boost also has their ASIO library to do sockets for you.

like image 139
GManNickG Avatar answered Oct 22 '22 08:10

GManNickG