I have the following char array:
char* a = new char[6]{0};
Which in binary is:
00000000 00000000 00000000 00000000 00000000 00000000
I also have an integer:
int i = 123984343;
Which in binary is:
00000111 01100011 11011001 11010111
I would like to insert this 4-byte-integer i
into the char array a
from position [1]
to position [4]
so that the original array a
becomes:
00000000 00000111 01100011 11011001 11010111 00000000
What is the quickest and easiest method to do that?
Use the copy
algorithm and a cast to char to access the underlying byte sequence:
#include <algorithm>
#include <cstdint>
std::uint32_t n = 123984343;
char * a = new char[6]{};
{
const char * p = reinterpret_cast<const char *>(&n);
std::copy(p, p + sizeof n, a + 1);
}
In this case I am assuming that you are guaranteeing me that the bytes of the integer are in fact what you claim. This is platform-dependent, and integers may in general be laid out differently. Perhaps an algebraic operation would be more appropriate. You still need to consider the number of bits in a char
; the following code works if uint8_t
is supported:
std::uint8_t * p = reinterpret_cast<std::uint8_t *>(a);
p[1] = n / 0x1000000;
p[2] = n / 0x0010000;
p[3] = n / 0x0000100;
p[4] = n / 0x0000001;
You can solve the problem as asked with
memcpy( &a[1], &i, sizeof(i) );
but I bet dollars to doughnuts that this is not the best way of solving your problem.
for (size_t ix = 0; ix < 4; ix++)
{
a[1+ix] = (static_cast<unsigned int>(i) >> (8*ix)) & 0xff;
}
Is a safe way of serializing an int
which fits into four bytes into a character array. Neither this end, nor the other end, have to make non-portable assumptions.
I'm not convinced that even this is the best way of solving your actual problem (but it hard to tell without more information).
If int is of 4 bytes, then copy the int to address of 2nd position in the char array.
int i = 123984343;
char* a = new char[6]{0};
memcpy(a+1, &i, sizeof(i));
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.