0

I'm trying to convert this php code:

$scriptpubkey = '4104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac'
$values = unpack("C*", pack("H*", $scriptpubkey));

to python. So far, i have done the following:

PHP: pack("H*", $scriptpubkey) -> Python: binascii.unhexlify(scriptpubkey)

I am not sure if it's correct though. If someone could explain the pack, unpack functions and what the characters "C*", "H*" do, it would be much appreciated.

2 Answers 2

0

If someone could explain the pack, unpack functions

The PHP manual covers pack and unpack

Pack given arguments into a binary string according to format.

Unpacks from a binary string into an array according to the given format.

So I would expect the code to produce a character array. This might be useful in PHP but not useful in Python.

The format characters are explained under pack

Code Description
a NUL-padded string
A SPACE-padded string
h Hex string, low nibble first
H Hex string, high nibble first
c signed char
C unsigned char
s signed short (always 16 bit, machine byte order)
S unsigned short (always 16 bit, machine byte order)

etc

However I would avoid performing a statement by statement or function by function translation and try to understand what the whole section of code is trying to achieve and then work out how best to accomplish that using the standard libraries available in Python. I find libraries and idioms vary greatly from language to language and an overly literal translation can end up being fragile, inefficient and incomprehensible. Your experience may differ though.

Note that you are asking about PHP and Python rather than about Bitcoin specifics. This question might do better on stackoverflow.com.

0

These pack/unpack php functions seem to be exactly as the identically named perl functions.

So pack("H*", ...) converts an ascii string to an byte-string.

And unpack("C*", ...) converts a byte-string to an array of byte values.

In python, pack("H*", $scriptpubkey) would be: binascii.a2b_hex(scriptpubkey)

The second step is not needed in python, since byte-arrays are already lists of byte values in python. If you access a single element: a[0] you would get the integer value 0x41 in this case. While accessing a subrange: a[1:] would get you a byte-array containing the pubkey.

Then another remark, if your variable contains a hexadecimal representation of your script, it might be clearer to indicate that in the variablename, for instance by naming it hex_scriptpubkey.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.