I need to get the length of input which is an integer in bytes

function mine(string s , uint i ) public view returns () {
        return (length of i);
  • 3
    What do you mean by the length of an integer? The decimal string length (for example 123456 has length 6) or the hexadecimal byte length (for exampple 0x1199FF has length 3)? Or something else? – Jesse Busman Jul 25 '18 at 9:33
  • It is an integer – Divya Galla Jul 25 '18 at 10:08

If you want to get the amount of bytes needed to represent the number, you can use a loop to count the amount of times you must shift 8 bits to the right to reach 0:

uint256 length = 0;
uint256 tempI = i;
while (tempI != 0) { tempI >>= 8; length++; }

This will give these results:

length == 0 when i == 0x0000000000

length == 1 when i == 0x0000000044

length == 2 when i == 0x0000000555

length == 2 when i == 0x0000006666

length == 3 when i == 0x0000778899

If you want to count the amount of bits occupied by the number, you can shift by 1 instead of 8: tempI >>= 1

  • 1
    Wow, great work. You should have received an accept, me – Jesse Busman Dec 16 '19 at 18:36

In Solidity uint is an alias of uint256. Its length is fixed. uint256 is made up of 256 bits, which is 32 bytes. So, a uint always has a length of 32 bytes. It does not make sense to calculate the length of it.

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.