pragma solidity 0.4.18; contract StringBytesPlayground { // convert a string less than 32 characters long to bytes32 function toBytes32(string _string, uint256 _memoryOffset) // pure means we are not accessing state nor changing state pure public returns (bytes32) { // make sure that the string isn't too long for this function // will work but will cut off the any characters past the 32nd character require(bytes(_string).length <= 32); bytes32 _stringBytes; // simplest way to convert 32 character long string assembly { // load the memory pointer of string with an offset of 32 // 32 passes over non-core data parts of string such as length of text _stringBytes := mload(add(_string, _memoryOffset)) } return _stringBytes; } // play around with the different data conversions that are happening // by uncommenting/commenting different returns function testBytesToChar(bytes32 _data, uint256 _offset) pure public returns (bytes1) // returns (bytes32) // returns (uint256 { return bytes1(bytes32(uint256(_data) * 2 ** (8 * _offset))); // return bytes32(uint256(_data) * 2 ** (8 * _offset)); // return uint256(_data) * 2 ** (8 * _offset); } // take bytes32 and return a string function toShortString(bytes32 _data) pure public returns (string) { // create new bytes with a length of 32 // needs to be bytes type rather than bytes32 in order to be writeable bytes memory _bytesContainer = new bytes(32); // uint to keep track of actual character length of string // bytes32 is always 32 characters long the string may be shorter uint256 _charCount = 0; // loop through every element in bytes32 for (uint256 _bytesCounter = 0; _bytesCounter < 32; _bytesCounter++) { /* TLDR: takes a single character from bytes based on counter convert bytes32 data to uint in order to increase the number enough to shift bytes further left while pushing out leftmost bytes then convert uint256 data back to bytes32 then convert to bytes1 where everything but the leftmost hex value (byte) is cutoff leaving only the leftmost byte */ bytes1 _char = bytes1(bytes32(uint256(_data) * 2 ** (8 * _bytesCounter))); // if the character is not empty if (_char != 0) { // add to bytes representing string _bytesContainer[_charCount] = _char; // increment count so we know length later _charCount++; } } // create dynamically sized bytes array to use for trimming bytes memory _bytesContainerTrimmed = new bytes(_charCount); // loop through for character length of string for (uint256 _charCounter = 0; _charCounter < _charCount; _charCounter++) { // add each character to trimmed bytes container, leaving out extra _bytesContainerTrimmed[_charCounter] = _bytesContainer[_charCounter]; } // return correct length string with no padding return string(_bytesContainerTrimmed); } }
0.4.18