Unpacking a hex value

Matthew Diephouse fokke_wulf at hotmail.com
Sat May 18 10:00:02 EDT 2002


> I get the impression you are trying to do something slightly 
> different than what either of these solutions gives you, so maybe
> you could give examples of input and desired output if that doesn't
> solve your problems.
> 
> -Peter

OK. I'm trying to open and decode some binary files. In order to do get 
the data, I need to break up parts of them into 1's and 0's, so I have a 
function hex2bin() that transform some of the data from hex to 1's and 
0's. I already have Perl code to do this, which I'll put below.

There are a couple things that are messing me up. Many of them are from 
pack/unpack, though some come from the differences between perl/ruby and 
python. Pack/unpack don't accept the format "H*", or the number of chars 
that I'm getting out of the perl functions.

sub hex2bin {	                      # For example data,
	my $out = hex( shift(@_) );   # $out = 21847 (after command)
	$out = pack("N", $out);       # $out = UW
	$out = unpack("B32", $out);
	# $out = 00000000000000000101010101010111
	$out = substr $out, -16, 16;  # $out = 0101010101010111
	return split "", $out;
}

There's my function in perl. What I've been trying in python is:

def hex2bin(input):
	output = int( input, 16)
	output = pack("!l", output)
	output = unpack("B" * (len(input) / calcsize("B")), output)
	# ----------------^
	# "B32" gives me an error

	print output
	output = output[-16:16]
	return output.split("")	

So how should the python code look?

      md |- m:att d:iephouse




More information about the Python-list mailing list