开发者

Converting int array to char*

Is this po开发者_C百科ssible? I wanted to convert this into a char* so I could later retrieve this values.


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.


Yes, but you probably shouldn't.

Doing so will treat the ints as sequences of bytes. It is tempting to then pass these bytes to be written to files or across sockets. The problem is that that the result will not be portable. There is no guarantee that whatever computer reads those bytes will interpret them in the same way. The biggest issue is big-endian vs little-endian. Essentially, some computers put the most significant byte first whereas others put the least significant byte first. Switching between them will result in the number being read backwards.


You can use C-style, but in C++:

int arr[] = {0, 1, 2, 3, 4};
char* p_arr = reinterpret_cast<char*>(arr);


If you want a string, use std::string, not char*. If you want serialization, use <stringstream>.

#include <stringstream>

std::ostringstream packet_os;
for ( int i = 0; i < 5; ++ i ) packet_os << arr[ i ] << " ";
network_send( packet_os.str().c_str() ); // c_str() returns char*

On the other end:

network_receive( recv_buf );
std::istringstream packet_is( recv_buf->bytes );
for ( int i = 0; i < 5; ++ i ) packet_is >> arr[ i ];
assert ( packet_is ); // for debugging, check that everything was received OK


This what you're looking to do?

int list[5] = {1,2,3,4,5};

char * pChar = (char *)list;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜