Created
July 31, 2013 23:32
-
-
Save jcramirez/6127185 to your computer and use it in GitHub Desktop.
A class I wrote as an utility when dealing with byte data. It can create bytes out of nibbles, words out of bytes and break words into a byte lists. All inputs are validated and the exceptions are raised.
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
class HexTools(): | |
""" | |
Performs simple operations on byte or word data | |
""" | |
MAX_VALUE_FOR_BYTE = 0xFF | |
MAX_VALUE_FOR_WORD = 0xFFFF | |
MAX_VALUE_FOR_NIBBLE = 0x0F | |
@staticmethod | |
def getHighNibbleFromByte(byte=0): | |
if byte > HexTools.MAX_VALUE_FOR_BYTE: | |
raise ValueError("value must be an integer less than 256") | |
if not isinstance(byte, int): | |
raise ValueError("value must be an integer less than 256") | |
byte = (byte >> 4) & 0x0F | |
#print hex(byte) | |
return byte | |
@staticmethod | |
def getLowNibbleFromByte(byte=0): | |
if byte > HexTools.MAX_VALUE_FOR_BYTE: | |
raise ValueError("value must be an integer less than 256") | |
if not isinstance(byte, int): | |
raise ValueError("value must be an integer less than 256") | |
byte = (byte) & 0x0F | |
#print hex(byte) | |
return byte | |
@staticmethod | |
def getWordFromBytes(msb=0x00, lsb=0x00): | |
""" | |
raises TypeError | |
""" | |
word = msb << 8 | |
word += lsb | |
return word | |
@staticmethod | |
def getByteFromNibbles(ms, ls): | |
""" | |
raises TypeError | |
""" | |
if ms > HexTools.MAX_VALUE_FOR_NIBBLE or ls > HexTools.MAX_VALUE_FOR_NIBBLE: | |
raise TypeError | |
byte = (ms << 4) & 0xF0 | |
byte |= ls | |
return byte | |
@staticmethod | |
def getByteListFromWord(word): | |
""" | |
raises TypeError | |
""" | |
if word > HexTools.MAX_VALUE_FOR_WORD: | |
raise TypeError | |
highByte = (word >> 8) & 0x00FF | |
lowByte = (word) & 0x00FF | |
byteList = [] | |
byteList.append(highByte) | |
byteList.append(lowByte) | |
return byteList |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment