How to convert from binary to bytes to hex in Python 3? -
i'm trying write program converts 2 hex strings bytes, , bytes binary. once in binary, want perform xor transposition on them. having been accomplished, want convert binary strings bytes, , again hex. know answer should be, it's question of getting b.
the code have far follows:
input1 = "1c0111001f010100061a024b53535009181c" input2 = "686974207468652062756c6c277320657965" target = "746865206b696420646f6e277420706c6179" d = conversions.hexconvert(input1) e = conversions.hexconvert(input2) print(d) print(e) f = bitstring.bitarray(d) g = bitstring.bitarray(e) xor1 = f.bin xor2 = g.bin print("xor1 is", xor1) print("xor2 is", xor2) xor1, xor2 = xor2, xor1 print("xor1 now:", xor1)
the function "hexconvert" comprised of following code:
import codecs def hexconvert(input): output = codecs.decode(input, 'hex') return(output)
my code spitting out following:
b'\x1c\x01\x11\x00\x1f\x01\x01\x00\x06\x1a\x02kssp\t\x18\x1c' b"hit bull's eye" xor1 : 000111000000000100010001000000000001111100000001000000010000000000000110000110100000001001001011010100110101001101010000000010010001100000011100 xor2 : 011010000110100101110100001000000111010001101000011001010010000001100010011101010110110001101100001001110111001100100000011001010111100101100101 xor1 now: 011010000110100101110100001000000111010001101000011001010010000001100010011101010110110001101100001001110111001100100000011001010111100101100101
all far. i'd know can add end of code convert xor1 bytes hex can compare result should be. i've been trying figure out how use struct, binascii, , bitstring, i'm getting nowhere. , suggestions appreciated.
it great if suggest how make code more efficient.
thanks in advance!
you don't have convert bits here; can xor bytes
fine. when iterate on bytes
object individual values integers in range 0-255, , can xor those. vice versa, can create new bytes
object again sequence of integers.
convert hex bytes binascii.unhexlify()
, again binascii.hexlify()
:
from binascii import hexlify, unhexlify bytes1, bytes2 = unhexlify(input1), unhexlify(input2) xor_bytes = bytes([b1 ^ b2 b1, b2 in zip(bytes1, bytes2)]) result = hexlify(xor_bytes).decode('ascii')
the decode there convert bytes
output of hexlify
string.
demo:
>>> binascii import hexlify, unhexlify >>> input1 = "1c0111001f010100061a024b53535009181c" >>> input2 = "686974207468652062756c6c277320657965" >>> bytes1, bytes2 = unhexlify(input1), unhexlify(input2) >>> xor_bytes = bytes([b1 ^ b2 b1, b2 in zip(bytes1, bytes2)]) >>> xor_bytes b"the kid don't play" >>> hexlify(xor_bytes).decode('ascii') '746865206b696420646f6e277420706c6179'
Comments
Post a Comment