Index

Solidity

  1. types
  2. External
  3. Library
    1. self in Library
    2. using * for
    3. self example
  4. interfaces
  5. import
  6. msg.value
  7. Handling ether
  8. Erc20 token in contract
  9. assembly
  10. Enum
  11. memory, storage, calldata
  12. Array Pushing
  13. length in array
  14. Struct array
  15. mapping
  16. bytes and string
  17. uint to bytes32
  18. returns with name
  19. score voting
  20. Tests
    1. Async Tests
    2. Hooks

bytes and string


bytes and strings as Arrays
Variables of type bytes and string are special arrays. A bytes is similar to byte[], but it is packed tightly in calldata and memory. string is equal to bytes but does not allow length or index access.
Solidity does not have string manipulation functions, but there are third-party string libraries. You can also compare two strings by their keccak256-hash using keccak256(abi.encodePacked(s1)) == keccak256(abi.encodePacked(s2)) and concatenate two strings using abi.encodePacked(s1, s2).
You should use bytes over byte[] because it is cheaper, since byte[] adds 31 padding bytes between the elements. As a general rule, use bytes for arbitrary-length raw byte data and string for arbitrary-length string (UTF-8) data. If you can limit the length to a certain number of bytes, always use one of the value types bytes1 to bytes32 because they are much cheaper.


bytes32

in solidity


bytes32 value must have 0x (Hexadecimal) before it:
e.g.
0xa75f4636202547e6a2994bed93e6ec3784a331160024269e7d39089bfa35bf2c


But:
Bytes32 is exactly 32 bytes long. It takes exactly one 32-byte word to represent a bytes32 because there's no need to set any space aside to encode the length. The length is always 32. A bytes with 32 bytes of data needs additional encoding to deal with variable length.

1 hexadecimal = 4 bits
8 bits = 1 bytes

This example hexcode has 64 hexadecimal places, so 64*4 bits.

Using conversion factors:
64*4 bits * 1 bytes / 8 bits = 64/2 bytes = 32 bytes



bytes also take hexadecimal, not strings:
pragma solidity >=0.4.22 <0.7.0;
pragma experimental ABIEncoderV2;


contract BytesTest {
    
    bytes public value;
    
    function setValue(bytes memory _value) public {
        value = _value;
    }
}


Hex value for Amiya:
https://onlineutf8tools.com/convert-utf8-to-bytes

images/816-1.png