Python Forum

Full Version: How do I mask Hex value wiht 0xFF?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello ,
I have this list
My List ['0x5b', '0x1ab', '0x282', '0x140', '0x6d7', '0x170']
0x5b<class 'str'>
0x1ab<class 'str'>
0x282<class 'str'>
0x140<class 'str'>
0x6d7<class 'str'>
0x170<class 'str'>
I want\need to maks all values with 0xFF

so the finall list will be
0x5b
0xab
0x82
0x40
0xd7
0x70
*********
there is no way to delete this post , I have found how to do it

while i < 6:
    temp= int(MyList[i], 16)
    temp = temp & int(0xff)
    MyList[i] = hex(temp)
    print(MyList[i])
    i += 1
Thanks,
A couple ways you could do it. Since you're starting with strings, just treat them as strings. Print the last two letters of each.

Otherwise, you could convert the strings into a number, mask it off, then print the hex version of that number.

hex_in = ['0x5b', '0x1ab', '0x282', '0x140', '0x6d7', '0x170']

# string manipulation
for hex_string in hex_in:
    print(f"0x{hex_string[-2:]}")

print()

# numeric manipulation
for hex_string in hex_in:
    num = int(hex_string, 16)
    print(hex(num & 0xff))
Convert to int first.
>>> hex(int('0x1ab', 0) & 255)
'0xab'
That said, I have the feeling that you should be working with bytes from the very beginning instead of str.