0

Using @polkadot-js/api, one can encode a string aabbcc into 0x18616162626363

> u8aToHex(api.createType('String', "aabbcc").toU8a())
"0x18616162626363"

I know that SCALE encoding adds the length info at the beginning of the encoded result, so in total the output is 7 bytes instead of 6.

However, when I try decode the output back to a string, the leading byte is treated as part of the string instead of being stripped out.

> api.createType('String', "0x18616162626363").toString()
"\x18aabbcc"

The expected result should be aabbcc without the initial \x18 byte.

So, how to get rid of the leading byte when decoding a SCALE-encoded string?

1 Answer 1

1

You want to follow the same steps you took to generate the hex to get back.

In your example generating the hex you do:

  1. String: "aabbcc"
  2. toU8a: Uint8Array(7) [ 24, 97, 97, 98, 98, 99, 99 ]
  3. toHex: 0x18616162626363

On the way back, just do the same:

  1. Hex string: "0x18616162626363"
  2. toU8a: hexToU8a("0x18616162626363")
  3. createType

So:

api.createType("String", hexToU8a("0x18616162626363")).toString()
> "aabbcc"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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