Reputation: 23
I want to copy an unsigned long integer to char buffer byte by byte. If I use the line under comment, it is not copied to buffer.
char buf[128];
//unsigned long int_val = 268435456;
unsigned long int_val = 293456376;
cout << "Value of int_val: " << int_val << endl;
memset(buf, 0, sizeof(buf));
memcpy(buf, &int_val, sizeof(long));
cout << "Value after unsigned long int copy - buf: " << buf << endl;
const int len = strlen(buf);
cout << "buf" << endl << "====" << endl;
for (int i = 0; i < len; i++)
{
printf("%3d (0x%02X)\n", buf[i], buf[i]);
}
Following is the output of two runs with each value:
Value of int_val: 268435456
Value after unsigned long int copy - buf:
buf
===
Value of int_val: 293456376
Value after unsigned long int copy - buf: ��}
buf
===
-8 (0xFFFFFFF8)
-55 (0xFFFFFFC9)
125 (0x7D)
17 (0x11)
Upvotes: 2
Views: 679
Reputation: 238461
it is not copied to buffer.
Yes it is.
cout << ... << buf << endl; const int len = strlen(buf);
It is unclear why you didn't expect the output that you see. 0 is the value of the null terminator character. If the lowest memory order byte of the integer is 0, then the buffer contains the null terminated string that represents the empty string. In such case, the output that you see is to be expected. On little endian systems (and also on big endian systems where long
is wider than 4 bytes) that happens to be the case for 268435456 which is 0x10'00'00'00 in hexadecimal.
Just because the bytes that you copied represent the empty string, doesn't mean that the bytes weren't copied.
Upvotes: 5
Reputation: 224311
In hexadecimal, 268435456 is 1000000016. Your C++ stores the bytes of an unsigned long
in memory with the low-value byte earlier in memory, so this is stored in memory as bytes with values 0016, 0016, 0016, 1016.
memcpy
correctly copies these bytes into buf
.
Then, when strlen(buf)
examines buf
, it finds a null byte (0016) first. This indicates the character string in buf
has zero length, as the terminating character appears immediately at the beginning. So strlen(buf)
returns zero.
Since this return value is assigned to len
, the loop for (int i = 0; i < len; i++)
performs zero iterations.
Similarly, in cout << "Value after unsigned long int copy - buf: " << buf << endl;
, buf
contains a string of zero length, so no characters are printed for it.
Upvotes: 4