Hi guys, i hope i'm phrasing the title right, I have a struct with a couple of uint32_t types, in those 32 bits i store multiple values, some are 2-bit values some are 4-bit some are 7 bit some are 1-bit and so on, this struct gets stored to EEPROM hence why i went with 32-bit unsigned ints to store these values to save EEPROM space rather than using a uint8_t for a value that will never use more than 2-bits or 4-bits etc.
Because of this i have to use bit manipulation to read these values, so to read say bits 25,26,27 as a 3-bit value since it will never go above the number 7 I do something like this:
Easy enough, i reads the data properly.
The issue i'm having tho is writing a value to that location, in javascript i use 2 functions, one to clear the bits and one to write to them
This works perfectly! I tried to do the same thing in C++ by using macros
However that does nothing in c++ i'm unable to write any data to it.
So now my question is, is this the right approach to write a set of bits to a larger type in C++?
Hoepfully i was able to word this post properly as i suck at explain things lol
Thank you in advance.
Because of this i have to use bit manipulation to read these values, so to read say bits 25,26,27 as a 3-bit value since it will never go above the number 7 I do something like this:
Code:
(myStruct.data1>>25) & 0x07;
Easy enough, i reads the data properly.
The issue i'm having tho is writing a value to that location, in javascript i use 2 functions, one to clear the bits and one to write to them
Code:
// clear the bits
myStruct.data1 = CLEAR_BITS_TO_LOCATION( myStruct.data1, 0x07, 25 );
// write the bits
myStruct.data1 = WRITE_BITS_TO_LOCATION( myStruct.data1, value & 0x07, 25 );
function CLEAR_BITS_TO_LOCATION(target, value, shift=0){
return (target &= ~(value << shift)) >>> 0;
}
function WRITE_BITS_TO_LOCATION(target, value, shift=0){
return (target |= (value << shift)) >>> 0;
}
This works perfectly! I tried to do the same thing in C++ by using macros
Code:
#define CLEAR_BITS_TO_LOCATION(target, value, shift) (target &= ~(value << shift))
#define WRITE_BITS_TO_LOCATION(target, value, shift) (target |= (value << shift))
CLEAR_BITS_TO_LOCATION(myStruct.data1,0x07,25);
WRITE_BITS_TO_LOCATION(myStruct.data1,value & 0x07,25);
However that does nothing in c++ i'm unable to write any data to it.
So now my question is, is this the right approach to write a set of bits to a larger type in C++?
Hoepfully i was able to word this post properly as i suck at explain things lol
Thank you in advance.
Last edited: