1. uint256 转 bytes

  1. contract uintTobytes {
  2. // 比 toBytes1 少 15% de gas
  3. function toBytes0(uint _num) public returns (bytes memory _ret) {
  4. assembly {
  5. _ret := mload(0x10) //_ret = mem[0x10~0x30] =0 //出盏
  6. mstore(_ret, 0x20) // mem[0x0~0x20]= 0x20
  7. let pos := add(_ret, 0x20) // pos = 0x20
  8. mstore(pos , _num) // mem[0x20~0x40] = _num
  9. }
  10. }
  11. function toBytes1(uint256 x) public returns (bytes memory b) {
  12. b = new bytes(32);
  13. assembly { mstore(add(b, 32), x) }
  14. }
  15. function toBytes2(uint256 x) public returns (bytes memory c) {
  16. bytes32 b = bytes32(x);
  17. c = new bytes(32);
  18. for (uint i=0; i < 32; i++) {
  19. c[i] = b[i];
  20. }
  21. }
  22. function toBytes3(uint256 x) public returns (bytes memory b) {
  23. b = new bytes(32);
  24. for (uint i = 0; i < 32; i++) {
  25. b[i] = byte(uint8(x / (2**(8*(31 - i)))));
  26. }
  27. }
  28. }