Daniel Lidström wrote:
> Hello!
>
> I want to work with individual bytes of integers. I know that ints are
> 32-bit and will always be. Sometimes I want to work with the entire
> 32-bits, and other times I want to modify just the first 8-bits for
> example. For me, I think it would be best if I can declare the 32-bits
> like this:
>
> unsigned char bits[4];
>
> When I want to treat this as a 32-bits integer, can I do something
> like this?
>
> unsigned int bits32 = *((unsigned int*)bits);
Yes but not like this because array bits is not initialised.
> I'm unsure of the syntax. I don't need to work in-place so to speak. It is
> fine to work with a copy.
What you can do is read an unsigned int or any other POD type as a
sequence of unsigned chars (or plain chars) - that is bytes, copy it
byte by byte to another unsigned char sequence (which includes possible
padding bits), and deal the new char sequence as another unsigned int.
The following example uses an int and is portable:
#include <iostream>
int main()
{
int integer=0;
unsigned char *puc= reinterpret_cast<unsigned char *>(&integer);
unsigned char otherInt[sizeof(integer)];
// Read integer byte by byte and copy it to otherInt
for(unsigned i=0; i<sizeof(integer); ++i)
otherInt[i]= puc[i];
// We treat the new unsigned char sequence as an int
int *p= reinterpret_cast<int *>(otherInt);
// Assign another value to the integer otherInt!
*p=7;
std::cout<<*p<<"\n";
}
--
Ioannis Vranos
http://www23.brinkster.com/noicys