PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 11, 2022

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

 August 11, 2022     binary, decimal, hex, python     No comments   

Issue

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.


Solution

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.



Answered By - Chathan Driehuys
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing