1

I'm new to Ethereum so please excuse my ignorance. Ethereum seems to have an ABI serialization protocol called Solidity. The spec is here: https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI

I'm looking for a way to encode and decode contracts in C#. Specifically, I want to take an array of bytes (byte[]) and convert it in to a human readable Ethereum address as a starting point.

Here are a couple of libraries that I've cloned, but after sifting through the code, it's not immediately apparent how to achieve what I am trying to do:

https://github.com/Nethereum/Nethereum

https://github.com/sense2k/Ethereum.NET

Can someone point me to an example of how to convert a byte array to a human readable Ethereum string address?

1 Answer 1

0

In Solidity:

Example of turning an Address into a Byte Array and then into a String:

/// @dev Function convert a Address to a String
/// @return Address as a string
function toString(address input) internal pure returns (string) {
    bytes memory byteArray = new bytes(20);
    for (uint i = 0; i < 20; i++) {
        byteArray[i] = byte(uint8(uint(input) / (2**(8*(19 - i)))));
    }
    return string(byteArray);
}

In C#:

Turning byte array into a String:

string address = System.Text.Encoding.UTF8.GetString(addrByteArray, 0, addrByteArray.Length);

Where addrByteArray is the Address in Byte Array format.

Hope that helps.

4
  • Thanks. I tried that but all I get back is garbled characters. The array that I am getting - in this case from my Trezor, is not encoded in UTF8 format. Dec 29, 2017 at 0:35
  • what is the meaning of uint(input) here? Isn't input an array of bytes? Does't uint(input) convert the array to an array of uints? Dec 29, 2017 at 0:36
  • The uint is the array index counter (like for i = 0; i++, but for Solidity). It extracts each byte out of the array, so long as that array is below 20 (an address will return a 20 byte array). Dec 29, 2017 at 0:57
  • Sorry about my ignorance. But, isn't "i" the array index counter? In this case, there is a piece of code uint(input) . What operation does that perform? Dec 29, 2017 at 1:20

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.