0

Does anyone have the 'somefunc' below to store bytes (specifically bytes4) as a string? Ideally something to get method_s in the code below:

contract Test{
  bytes4 public method;
  string public method_s;

  function Test() {
    method = this.get_f.selector;
  }

  function makeString(){
   method_s = somefunc(method);
  }

}

So I need method = 0x0cb9ef7a and method_s = "0x0cb9ef7a"

Many thanks in advance

2

This code will convert a bytes4 to an hexadecimal string

function toHexDigit(uint8 d) pure internal returns (byte) {                                                                                      
    if (0 <= d && d <= 9) {                                                                                                                      
        return byte(uint8(byte('0')) + d);                                                                                                       
    } else if (10 <= uint8(d) && uint8(d) <= 15) {                                                                                               
        return byte(uint8(byte('a')) + d - 10);                                                                                                  
    }                                                                                                                                            
    revert();                                                                                                                                    
}                                                                                                                                                

function fromCode(bytes4 code) public view returns (string) {                                                                                    
    bytes memory result = new bytes(10);                                                                                                         
    result[0] = byte('0');
    result[1] = byte('x');
    for (uint i=0; i<4; ++i) {
        result[2*i+2] = toHexDigit(uint8(code[i])/16);
        result[2*i+3] = toHexDigit(uint8(code[i])%16);
    }
    return string(result);
}
2
  • Works like a charm. I was working at it trying to use assembly, but this is a solid. Thanks for the effort – thefett Apr 25 '18 at 1:56
  • 1
    It should not be hard to write assembly directly, but short string have a particular encoding than can be annoying, look at this article for the deailt of string & arrays storage medium.com/@hayeah/…. – Ismael Apr 25 '18 at 2:10

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.