Home > Software design >  Converting from decimal to hexadecimal for ELROND blockchain
Converting from decimal to hexadecimal for ELROND blockchain

Time:07-30

I am trying to do some smart contract testing for Elrond blockchain with multiple wallets and different token amounts.

The Elrond blockchain requires some hexadecimal encodings for the Smart Contract interaction. The problem is that my hex encoding matches some conversions like in this webpage http://207.244.241.38/elrond-converters/ but some others are not:

For example here is my for loop:

for line in $file; do
    MAIAR_AMOUNT=$(echo $line | awk -F "," '{print $2}')

    MAIAR_AMOUNT_HEX=$(printf "x" $MAIAR_AMOUNT)

    echo -e "$MAIAR_AMOUNT > $MAIAR_AMOUNT_HEX"
done

And here is the output

620000000000 > 905ae13800
1009000000000 > eaed162a00
2925000000000 > 2a907960200
31000000000 > 737be7600
111000000000 > 19d81d9600

The first one is the decimal value I want to convert, the second is the hexadecimal. Now if I compare the results with http://207.244.241.38/elrond-converters/

A value like 2925000000000 is 02a907960200 not 2a907960200 like I have in my output. (notice the 0 at the beginning)

But a value like 620000000000 is matching with the website 905ae13800

Of course adding a 0 in front of x is not gonna help me.

Now if I go to this guy repository (link below) I can see there is a calculus made, but I don't know JavaScript/TypeScript so I don't know how to interpret it in Bash.

https://github.com/bogdan-rosianu/elrond-converters/blob/main/src/index.ts#L30

CodePudding user response:

The 4 in x is how many digits to pad the output to. Use 2x to pad the output to 12 hex digits.

❯ printf '2x' 2925000000000
02a907960200

CodePudding user response:

It looks the converted hex string should have even number of digits. Then would you please try:

MAIAR_AMOUNT_HEX=$(printf "%x" "$MAIAR_AMOUNT")
(( ${#MAIAR_AMOUNT_HEX} % 2 )) && MAIAR_AMOUNT_HEX="0$MAIAR_AMOUNT_HEX"

The condition (( ${#MAIAR_AMOUNT_HEX} % 2 )) is evaluated to be true if $MAIAR_AMOUNT_HEX has odd length. Then 0 is prepended to adjust the length.

  • Related