Moutside
Moutside

Reputation: 3

How to handle and convert different bases in Python without parsing them into Strings?

I have a number in hex that I need to convert into binary, to be able to perform bitwise operations on it. The problems is that all the functions I found that convert numbers into binary - like format() - return strings, but I need the number in a data type that can be manipulated like binary.

Found fomrat(), but that returns Strings. I found int(), which can turn it into an integer, but can't find an equivalent for binary.

What I'm trying to do is for example: add 1 to 0b0001 and get the sum as 0b0010 and I did not find a way of doing it when 0b0001 is a String.

Upvotes: 0

Views: 108

Answers (1)

Chathan Driehuys
Chathan Driehuys

Reputation: 1213

No matter how you input an integer, Python treats it the same. That means you can do math exactly how you expect. For example:

hex_num = 0xff

# We can show its binary equivalent
format(hex_num, 'b')

# We can also do math with it
result = hex_num + 1
# including bitwise operations
result2 = hex_num << 1

You can then output the result in any format you want using functions like format or bin that you have already found. The key is that there is no difference internally between a "hex number", a "binary number", or a normal integer.

Upvotes: 2

Related Questions