-
Registers
I have a 16 bit register (0-15). I want to store a 10 bit number in bits 5-14 as bits 0-4 are reserved. When I use the left shift operator the number multiplies by 32, therefore when I read the register I have stored a different value. Is there a way around this?
-
is this a hardware register or a defined by you register. If the latter you can define it as a bit field then you will be able to do what you want with the bits you want to play with and leave the reserved bits alone.
-
If you want to preserve the bits already there, then you need to do a read/modify/write type operation.
Code:
int temp = reg; // read your register
temp = temp & 0x1F; // mask off all the bits you want to change
temp = temp | (new_value << 5); // add your new bits, shifted into the correct place
reg = temp; // assign back to your reg.
> If the latter you can define it as a bit field
If its an internal data structure, then this is OK, but it's far from portable if its an external register/data structure.
The layout of bit fields is compiler specific.