A C++ demonstration class that forces values to be stored in MSB format, suitable for use with Berkeley DB
#include <cstring> | |
// Forces values to be stored in MSB format | |
// Assumes 32 bit int! | |
class BdbOrderedInt | |
{ | |
private: | |
unsigned char bytes[4]; | |
public: | |
BdbOrderedInt(int val) | |
{ | |
setInt(val); | |
} | |
int getInt() const | |
{ | |
int val = 0; | |
for (int i=0; i<sizeof(bytes); i++) | |
{ | |
val <<= 8; | |
val |= bytes[i]; | |
} | |
return val; | |
} | |
void setInt(int val) | |
{ | |
for (int i=sizeof(bytes)-1; i>=0; i--) | |
{ | |
bytes[i] = (val & 0xff); | |
val >>= 8; | |
} | |
} | |
void operator=(int val) | |
{ | |
setInt(val); | |
} | |
operator int() const | |
{ | |
return getInt(); | |
} | |
unsigned char *getBytes() | |
{ | |
return bytes; | |
} | |
// Note: should return the same as sizeof(BdbOrderedInt) | |
size_t getSize() const | |
{ | |
return sizeof(int); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment