I have come across a C++ function in my work that extracts integer numbers from a 16bit unsigned integer using bit-masking.
I need to port this over to Python, and am unsure if the same syntax is valid between the languages, or if there are any special differences between the implementations.
My C++ function is this:
void BitMapper(unsigned int x){
unsigned int a=0;
unsigned int b=0;
unsigned int c=0;
unsigned int aMask=0xff00;
unsigned int bMask=0x00f0;
unsigned int cMask=0x000f;
a=(x & aMask)>>8;
b=(x & bMask)>>4;
c=(x & cMask);
std::cout<< a << "\t" << "b" << "\t"<< c <<std::endl;
}
I have very naively implemented it in Python as this:
def BitMapper(x, aMask=0xff00, bMask=0x00f0, cMask=0x000f):
###Missing some method to cast x as unsigned 16 bit unsigned integer
a = (x & aMask)>>8
b = (x & bMask)>>4
c = (x & cMask)
print("\t {0} \t {1} \t {2}".format(a, b, c))
Is this implementation correct? If not, what have I done wrong and why?
I would be clear that I have never come across bit-masking before, so if there are stupid mistakes, it is because I am already puzzled about what is going on here anyway.
I know my input is of the format:
a b c
00000000 | 0000 | 0000
and I assume that the <<
is doing a bit shift, presumably of the length of a and b by the values of the shift in the function definitions. As for the hexadecimal code of the masks, I have no idea what this means.
If someone could educate me on what exactly is going on in this function as well, I would be most appreciative.