Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

binascii.hexlify() returns binary as String and not Integer

I'm trying to teach myself python and am just generally messing about with it. I have come across a bit of an issue though.

Basically I'm trying to make something that will turn a string into binary, bit-shift it by x, and then return it to you as a new string.

The best Method I have found to achieve this seems to be binascii.hexlify(str).

The problem that I am getting is that this Method does seem to return the binary representation to me... but as a String??

I cannot call int() on the string, and I've tried multiple combinations of bin(int()) etc. I'm a bit stuck here guys, any help would be appreciated :-)

I know I'm probably going about this in the completely wrong way, but hey. I'm teaching myself so... :-)

See code so far below:

import binascii

password = raw_input("Enter your Password")
bits = int(raw_input("Shift By:"))

def getBinary(word):
    return bin(int(binascii.hexlify(word), 16))

def shift(bin, num):
    return bin << num

shift(getBinary(password), bits)
like image 546
Panomosh Avatar asked Oct 16 '25 00:10

Panomosh


1 Answers

bin(), hex() and so forth are just representations of numbers, in string form. To be able to do bitshifts etc, you keep your value as an integer! Remember, every piece of data within a computer is in binary anyway. Then convert it on output. The default output conversion for an int is to print it as a number in base 10, using digits 0-9 ;). Thus try the following

import binascii

password = raw_input("Enter your Password: ")
bits = int(raw_input("Shift By: "))

def getBinary(word):
    return int(binascii.hexlify(word), 16)

def shift(bin, num):
    return bin << num

shifted = shift(getBinary(password), bits)
print bin(shifted)


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!