I need to manipulate bits of all types for storing

I need a translate (in both directions) all primitive types, into char[] (will be stored in string)

I understand how to manipulate integral types with bits and I cant just cut them down and shift them, but float and double don't work with this manipulation. So does anyone know how I can create a perfect bit copy of float and double?

1
2
3
4
5
6
7
8
9
10
11
int i = 0xFCED03A4; //Random number
char c[4];
c[0] = ((i >> 3) & 0xFF);
c[1] = ((i >> 2) & 0xFF);
c[2] = ((i >> 1) & 0xFF);
c[1] = (i & 0xFF);

// c[0] = 0xFC
// c[1] = 0xED
// c[2] = 0x03
// c[3] = 0xA4 


This is basic stuff but I need an equivalent for float and double types, and it needs to be a perfect BIT copy, not value copy;

Thanks for any help
Lumpy-bump?
2 Days no answers :(
Sorry to seem so impatient.

Does anyone know whether memcpy(b2, sizeof(b2), b1, sizeof(b2)); would work? To create an exact copy of the bits stored in a float or double b1 and store it in a character array b2 ?
Last edited on
1
2
3
4
5
int i = 0xFCED03A4;
char * ch = (char*)&i;
int ch_size = sizeof(i);

// can access from ch[0] to ch[ch_size-1] 


This isn't going to be recommended by any standard rules, but it works.
To switch to float or double, just change from int to float or double, the code will still keep working.
Last edited on
This did come to mind but with using the reinterpret_cast to check for errors, however I thought that the compiler might complain, or that if this is allowed that maybe Windows would have rules about its memory handling and prevent this from working during runtime
Last edited on
I don't think there's anything that avoids this to be good on known systems like Windows.
Windows itself likes to cast pointers to other types (see Handles like HWND, HMODULE itself is a pointer to IMAGE_DOS_HEADER).

Also I think it should be reinterpret_cast.
dynamic_cast is for checking compatibility between virtual classes.
Last edited on
Whoops, yeah I meant reinterpret_cast, just got the names a little mixed up there in the explanation. Don'e worry, I know the difference.

Well if you're sure it'll work then thanks very much for the help!
I'm sure it will on Windows, because from what I know, Windows is always on a Little Endian system.
But don't ask me for ARM or similar, lol.
Topic archived. No new replies allowed.