Reputation: 407
How can I convert a string decimal to hex decimal and add them to char pointer? Why does the memcpy(value + 2, &value_value, value_length);
not work, the result is 0x02 0x01
and not 0x02 0x01 0x4f
.
#include <string.h> /* strlen */
#include <stdio.h> /* printf */
#include <stdint.h> /* int32_t */
#include <stdlib.h> /* strtol */
int main()
{
char value_type = 0x02;
char *value_value = "79"; /* Must convert to 4f */
char value_length;
int32_t num = strtol(value_value, NULL, 10);
if (num < 255)
value_length = 0x01;
else if (num < 65536)
value_length = 0x02;
else if (num < 16777216)
value_length = 0x03;
else if (num < 4294967295)
value_length = 0x04;
char *value = malloc(2 + value_length);
memcpy(value, &value_type, 1);
memcpy(value + 1, &value_length, 1);
memcpy(value + 2, &value_value, value_length);
/* expectation: 0x02 0x01 0x4f */
for (int i = 0; i < strlen(value); i++)
printf("%02x\n", value[i]);
return 0;
}
Upvotes: 0
Views: 279
Reputation: 1530
You are using wrong variable:
memcpy(value + 2, &num, value_length);
Also, you must not trait your value as string, as far as it uses binary value. Change your code to:
/* expectation: 0x02 0x01 0x4f */
int dumplen=len+2;
for (int i = 0; i < dumplen; i++)
printf("%02x\n", value[i]);
return 0;
Upvotes: 0
Reputation: 254926
memcpy(value + 2, &value_value, value_length);
this expression copies value_length
bytes from &value_value
.
Given that it's declared as
char *value_value
&value_value
is read as a pointer-to-a-pointer-to-a-char
. So effectively you're reading the pointer value.
How to solve:
memcpy(value + 2, &num, value_length);
Another problem with your code:
you're using strlen(value)
while value
is not a null-terminated C-string. It's just an array of bytes that you fill with your data.
How to fix:
don't use strlen
in this case, you know the size of the array: 2 + value_length
. For clarity you may put it to a separate variable.
Upvotes: 1