Reputation: 267
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).
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. I've also tried
int x;
static_cast<char*>(static_cast<void*>(&x));
with no luck. Any suggestions are appreciated!
Upvotes: 1
Views: 3105
Reputation: 1514
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
Upvotes: 0
Reputation: 12874
#include <string>
int i = 123;
char c[sizeof(int)];
std::memcpy(c,&i,sizeof(int));
Upvotes: 5