Guest User

Untitled

a guest
Apr 22nd, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. // take bytes32 and return a string
  2. function toShortString(bytes32 _data)
  3. pure
  4. public
  5. returns (string)
  6. {
  7. // create new bytes with a length of 32
  8. // needs to be bytes type rather than bytes32 in order to be writeable
  9. bytes memory _bytesContainer = new bytes(32);
  10. // uint to keep track of actual character length of string
  11. // bytes32 is always 32 characters long the string may be shorter
  12. uint256 _charCount = 0;
  13. // loop through every element in bytes32
  14. for (uint256 _bytesCounter = 0; _bytesCounter < 32; _bytesCounter++) {
  15. /*
  16. TLDR: takes a single character from bytes based on counter
  17. convert bytes32 data to uint in order to increase the number enough to
  18. shift bytes further left while pushing out leftmost bytes
  19. then convert uint256 data back to bytes32
  20. then convert to bytes1 where everything but the leftmost hex value (byte)
  21. is cutoff leaving only the leftmost byte
  22. */
  23. bytes1 _char = bytes1(bytes32(uint256(_data) * 2 ** (8 * _bytesCounter)));
  24. // if the character is not empty
  25. if (_char != 0) {
  26. // add to bytes representing string
  27. _bytesContainer[_charCount] = _char;
  28. // increment count so we know length later
  29. _charCount++;
  30. }
  31. }
  32.  
  33. // create dynamically sized bytes array to use for trimming
  34. bytes memory _bytesContainerTrimmed = new bytes(_charCount);
  35.  
  36. // loop through for character length of string
  37. for (uint256 _charCounter = 0; _charCounter < _charCount; _charCounter++) {
  38. // add each character to trimmed bytes container, leaving out extra
  39. _bytesContainerTrimmed[_charCounter] = _bytesContainer[_charCounter];
  40. }
  41.  
  42. // return correct length string with no padding
  43. return string(_bytesContainerTrimmed);
  44. }
Add Comment
Please, Sign In to add comment