...by Daniel Szego
quote
"Simplicity is the ultimate sophistication."
Leonardo da Vinci

Tuesday, April 3, 2018

Solidity Tips and Tricks - converting types


In solidity converting between types is not always very straightforward, as an example there is no typecast from address to string, there is no typecast bytes to string, and from bytes to address. If you need such a conversion, you have to implement it. The following example shows a possible implementation for such a conversions:

contract TypeCasting {
    
  function toString(address addr) returns (string) {
    bytes memory b = new bytes(20);
    for (uint i = 0; i < 20; i++) {
      b[i] = byte(uint8(uint(addr) / (2**(8*(19 - i)))));
    }
    return string(b);
  }
  
  function bytes32ToString(bytes32 x) constant returns (string) {
    bytes memory bytesString = new bytes(32);
    uint charCount = 0;
    for (uint j = 0; j < 32; j++) {
      byte char = byte(bytes32(uint(x) * 2 ** (8 * j)));
      if (char != 0) {
        bytesString[charCount] = char;
        charCount++;
      }
    }
    bytes memory bytesStringTrimmed = new bytes(charCount);
    for (j = 0; j < charCount; j++) {
      bytesStringTrimmed[j] = bytesString[j];
    }
    return string(bytesStringTrimmed);
  }
  
  function bytesToAddress(bytes _address) public returns (address) {
  uint160 m = 0;
  uint160 b = 0;

  for (uint8 i = 0; i < 20; i++) {
    m *= 256;
    b = uint160(_address[i]);
    m += (b);
  }
 }
}