I have a character pointer and need to store 2 byte values in memory using this pointer. Tried this
*dataConfigured = configuredParameterCount;
*++dataConfigured = configuredParameterCount << 8;
Is there any better code other than this?
Assuming:
char dataConfigured[2];
uint16_t configuredParameterCount = 4711;
you can do:
memcpy(dataConfigured, &configuredParameterCount, sizeof(dataConfigured));
if you have
char* dataConfigured = ..;
short data = 123;
you can do
*((short*)dataConfigured) = data;
Be careful - you need to make sure that there is enough memory reserved.
Assuming the type of configuredParameterCount
is short
(2 bytes), you can simply do this
*((short*)dataConfigured) = configuredParameter;
But do make sure that buffer pointed by dataConfigured
has enough space.
As pointed out by @Calvin, this may cause problem on some computer architectures (although it will work on most common ones, like x86 and x64). But if you want to be on all architectures memcpy
is safer bet (slower but safer).
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.