Created
August 29, 2012 23:09
-
-
Save brenttaylor/3520108 to your computer and use it in GitHub Desktop.
Byte Array to Integer Type
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
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