1

i know hexadecimal charchter ( 0 1 2 3 4 5 6 7 8 9 A B C D E F)

when i write code

string a= hex"011a" //it is ok 

but when write this code

string a=hex"011aa" // get Error 

why? and how can i take advantage of this in solidity

2 Answers 2

1

First, you need to add the characters in pairs, since a pair of hex digit is a byte.

The line that is showing an error has an uneven set of characters:

string a=hex"011aa" // get Error 

Better do this:

string a2 =hex"011a0a";

Also, the reason is that you need to add bytes whose values are within the range (in decimal) of 0-127. Because those are the value printable UTF-8 characters that Solidity support.

For example, look at this table: https://www.asciitable.com/

You will see that it goes from 0 to 127 in decimal. In hexadecimal, the range goes from 0-7F.

If you try this:

string a = hex"aa";

It will not work, because the decimal value of the hex aa is 170, and we know that it should not be greater than 127. So we are limited to the range 0-7F in hex:

string min_max_accii_value = hex"00_7f";

Do your own conversion here: https://www.rapidtables.com/convert/number/hex-to-decimal.html?x=aa

So, you can do something like this, and separate it with _ to make it more readable:

string a3 = hex"00_0a_7f";

Here the docs: https://docs.soliditylang.org/en/v0.8.11/types.html#unicode-literals

0

Although its really unclear what you're trying to do, when you do string x = hex'something', the compiler will look for UTF-8 characters that corresponds to the hex number you entered, and is therefore is expecting an even number of characters (2 hex characters = 1 byte). As for your 2nd question, i don't really understand it, sorry, you can... Use that to output non printable characters, i guess? (which is what you're doing with the 1st string, 01 and 1a are both non printable characters in UTF-8) But yeah, why would you do that?

Your Answer

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

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