Solidity中固定大小字节数组转string

in #solidity7 years ago

string本身是一个特殊的动态字节数组,所以它只能和bytes之间进行转换,不能和固定大小字节数组进行直接转换,如果是固定字节大小数组,需要将其转换为动态字节大小数组才能进行转换。

``
pragma solidity ^0.4.4;

contract C {

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 bytes32ArrayToString(bytes32[] data) constant returns (string) {
    bytes memory bytesString = new bytes(data.length * 32);
    uint urlLength;
    for (uint i = 0; i< data.length; i++) {
        for (uint j = 0; j < 32; j++) {
            byte char = byte(bytes32(uint(data[i]) * 2 ** (8 * j)));
            if (char != 0) {
                bytesString[urlLength] = char;
                urlLength += 1;
            }
        }
    }
    bytes memory bytesStringTrimmed = new bytes(urlLength);
    for (i = 0; i < urlLength; i++) {
        bytesStringTrimmed[i] = bytesString[i];
    }
    return string(bytesStringTrimmed);
}    

}
``

Sort:  

Try Our Service Before Buy🎁

  • Exclusive 30 days free upvotes to your every new post.
  • Limited Time Offer
  • No need to send any kinds of steem or sbd its full free service.
    we have paid service too so please check them too. Active the free upvote service and learn more about it here : JOIN NOW CLICK HERE

Attention!! don't click on the link eat a phishing site

thank you very much

Coin Marketplace

STEEM 0.15
TRX 0.16
JST 0.028
BTC 67011.69
ETH 2366.74
USDT 1.00
SBD 2.32