Skip to content

Instantly share code, notes, and snippets.

@Janaka-Steph
Created November 5, 2018 13:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Janaka-Steph/0202836ac3a1caf8b9359207df7379eb to your computer and use it in GitHub Desktop.
Save Janaka-Steph/0202836ac3a1caf8b9359207df7379eb to your computer and use it in GitHub Desktop.
Integer to Little endian hex Conversion Script for Bitcoin Script
#!/bin/bash
if [ -z $1 ];
then
echo "You must include an integer as an argument.";
exit;
fi
if (( $1 > "2147483647" )) || (( $1 < "-2147483647" ));
then
echo "Your number ($1) must be between -2147483647 and 2147483647";
exit;
fi
if [ $1 -lt 0 ];
then
integer=$(echo $((-$1)));
negative=1;
else
integer=$1;
negative=0;
fi
hex=$(printf '%08x\n' $integer | sed 's/^\(00\)*//');
hexfirst=$(echo $hex | cut -c1)
[[ 0x$hexfirst -gt 0x7 ]] && hex="00"$hex
lehex=$(echo $hex | tac -rs .. | echo "$(tr -d '\n')");
if [ "$negative" -eq "1" ];
then
lehex=$(printf '%x\n' $((0x$lehex | 0x80)))
fi
size=$(echo -n $lehex | wc -c | awk '{print $1/2}');
hexcodeprefix=$(printf '%02x\n' $size);
echo "Integer: $1";
echo "LE Hex: $lehex";
echo "Length: $size bytes";
echo "Hexcode: $hexcodeprefix$lehex";
@Janaka-Steph
Copy link
Author

Janaka-Steph commented Nov 5, 2018

cd /usr/local/bin
nano int2lehex
chmod 755 int2lehex

If you don't have the tac command on Mac:

  • brew install coreutils
  • ln -s /usr/local/bin/gtac /usr/local/bin/tac

Source: https://github.com/ChristopherA/Learning-Bitcoin-from-the-Command-Line/blob/master/08_2_Building_the_Structure_of_P2SH.md#appendix-the-integer-conversion-script

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment