[英]Store integer using character pointer
I have a character pointer and need to store 2 byte values in memory using this pointer. 我有一个字符指针,需要使用此指针在内存中存储2个字节的值。 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 假设
configuredParameterCount
的类型很short
(2个字节),则只需执行此操作
*((short*)dataConfigured) = configuredParameter;
But do make sure that buffer pointed by dataConfigured
has enough space. 但是,请确保由
dataConfigured
指向的dataConfigured
具有足够的空间。
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). 正如@Calvin指出的那样,这可能会在某些计算机体系结构上引起问题(尽管它可以在大多数常见的体系结构上运行,例如x86和x64)。 But if you want to be on all architectures
memcpy
is safer bet (slower but safer). 但是,如果要在所有体系结构上使用
memcpy
是更安全的选择(较慢但更安全)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.