Skip to content

Instantly share code, notes, and snippets.

@brenttaylor
Created August 29, 2012 23:09
Show Gist options
  • Save brenttaylor/3520108 to your computer and use it in GitHub Desktop.
Save brenttaylor/3520108 to your computer and use it in GitHub Desktop.
Byte Array to Integer Type
enum ByteOrder {
BIG_ENDIAN,
LITTLE_ENDIAN
};
enum BTIException {
INTEGER_WIDTH_OUT_OF_BOUNDS
};
template <typename IntType>
IntType BytesToInteger(const unsigned char* Bytes, const unsigned int& Length,
ByteOrder Endian = LITTLE_ENDIAN) throw (BTIException) {
const int IntegerWidth = sizeof(IntType);
if (Length < IntegerWidth)
throw INTEGER_WIDTH_OUT_OF_BOUNDS;
switch (Endian) {
case LITTLE_ENDIAN:
return *static_cast<IntType *>(Bytes);
case BIG_ENDIAN:
IntType result = 0;
for (unsigned int index = 0; index < IntegerWidth; index++)
result = (result << 8) + Bytes[index];
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment