Skip to content

Instantly share code, notes, and snippets.

@ddanderson
Created February 19, 2011 19:14
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
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
#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