简体   繁体   English

在C ++中从int获取byte []

[英]Get byte[] from int in c++

So in my C++ program I am trying to replicate the C# BitConverter.GetBytes() function, or at least find some method in which it will return same result, (btw I cannot use std::vector<unsigned char> which I've seen a few people recommend on other forums). 所以在我的C ++程序中,我试图复制C# BitConverter.GetBytes()函数,或者至少找到一些将返回相同结果的方法,(顺便说一句,我不能使用std::vector<unsigned char>看到有人在其他论坛上推荐)。

I'm using this so I can take an int and then get a byte[] of it then take that byte[] and use it to set memory at a particular memory address. 我正在使用它,所以我可以获取一个int ,然后获取其中的一个byte[] ,然后获取该byte[]并将其用于将内存设置为特定的内存地址。 I've also tried 我也尝试过

int x;
static_cast<char*>(static_cast<void*>(&x));

with no luck. 没有运气。 Any suggestions are appreciated! 任何建议表示赞赏!

#include <string>

int i = 123;
char c[sizeof(int)];
std::memcpy(c,&i,sizeof(int));

Another method would be 另一种方法是

union Value
{
   int val;
   char bytearray[sizeof(int)];
};

which does not use memcpy.Instead it allows a value in memory as different types 它不使用memcpy,而是允许内存中的值作为不同类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM