Convert int array to char *

Is it possible? I wanted to convert this to char * in order to get these values ​​later.

+4
source share
5 answers

Of course:

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

The valid range is c to c + sizeof(array) . You can do this with any type of POD.

You can drop from a sequence of bytes:

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

This is guaranteed. But it looks like you are trying to send stuff over the network, which may lead to other problems.


The process you are looking for is called serialization (and has a FAQ) . This is when you take an object, convert it to a series of bits, which can subsequently be "deserialized" to the original object.

Doing this work on multiple platforms can be difficult because you need to make sure that you serialize to a specific format and that each platform knows how to read it from that format. (For example, the big-endian platform can always be converted to little-endian before being sent and likewise converted back to big-endian upon receipt.) You cannot treat non-POD types as a stream of bytes (for example, std::string ), therefore you need to write serialization functions for those to convert their data to a stream of bytes and deserialization functions to convert them back.

I especially like that Boost does this, and if you can use their serialization library . They basically first define procedures for serializing fundamental types, then you can serialize more complex types by building them. Of course, Boost also has an ASIO library for creating sockets for you.

+7
source

Yes, but you probably shouldn't.

This will treat int as a sequence of bytes. It is tempting then to transfer these bytes to files or through sockets. The problem is that the result will not be portable. There is no guarantee that any computer reading these bytes will interpret them in the same way. The biggest problem is Bindian versus small-endian. In fact, some computers first place the most significant byte, while others first place the least significant byte. Switching between them will cause the number to be read back.

+3
source

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

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

If you need a string, use std::string , not char* . If you want to serialize, 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* 

At 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 
0
source

Is that what you want to do?

 int list[5] = {1,2,3,4,5}; char * pChar = (char *)list; 
-1
source

Source: https://habr.com/ru/post/1307619/


All Articles