1

Say I have the following address:

0x9dd1e8169e76a9226b07ab9f85cc20a5e1ed44dd

I can use this function to convert it to a bytes

function toBytes(address a) public constant returns (bytes b){
    assembly{
      let m := mload(0x40)
      mstore(add(m,20),xor(0x140000000000000000000000000000000000000000,a))   //20 bytes in an address
      mstore(0x40,add(m,52))
      b := m
    }
  }

It works great!

However, how can I just get the last 128 bits of the address and return a uint128?

e.g. this type of function signature:

function toUint128(address a) public constant returns (uint128 u){
    assembly{
      let m := mload(0x40)
      //what goes here??
      //??
      //??
      //mstore(add(m,20),xor(0x140000000000000000000000000000000000000000,a))
      //mstore(0x40,add(m,52))
      u := m
    }
  }

And I want the uint128 equivalent of "0x9dd1e8169e76a9226b07ab9f85cc20a5e1ed", where the last 4 hex chars ("44dd", 32 bits) are removed. This is a 160 bit number minus 32 bits = a 128 bit number.

Edit:

This is actually quite simple, all you have to do is:

uint160 x=uint160(myAddress);

  • Do you mean uint128 x=uint128(myAddress); ? Be aware of which end is being truncated and don't assume that an address is using all 20 bytes. For instance, some contracts like to burn to specific addresses like 0x0, 0xdeadbeef and 0x00000000000000000000000000000000deadbeef (3 completely different addresses). In such cases. If there is for some reason an address that uses limited byte information, it may get birthday collided with another after the casting to int128. – o0ragman0o Apr 2 '17 at 4:13
1

If you want an equivalent of "0x9dd1e8169e76a9226b07ab9f85cc20a5e1ed" - it is 160-16=144 bits ("44dd" == 16 bits). Function addressToUint144 will do the conversion.

contract AddressToUint144
{
    address public constant example_addr=0x9dd1e8169e76a9226b07ab9f85cc20a5e1ed44dd;

    function addressToUint144(address addr) constant
    returns (uint144)
    {
        return uint144(bytes20(addr)>>16);
    }

    //Converting to bytes18 only for good visualization in Remix
    function test()
    returns (bytes18)
    {
        return bytes18(addressToUint144(example_addr));
    }
}

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.