Created
February 19, 2011 19:14
-
-
Save ddanderson/835285 to your computer and use it in GitHub Desktop.
A C++ demonstration class that forces values to be stored in MSB format, suitable for use with Berkeley DB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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