Hot answers tagged

37

Your example shows storing an IPFS identity using it's alphanumeric encoding (Qm...), which is the same Base58 encoding that Bitcoin uses. However, what it's representing at its core is a number (the hash). Storing the identifier in the Base58 format needs to be a String because it includes letters (and what actually gets saved is the ASCII code for each ...


24

You can pass bytes parameters in Remix or browser-solidity as the array of single bytes, for example ["0x00","0xaa", "0xff"] is equivalent to "0x00aaff" Do not know why, but the Remix IDE and browser-solidity interprets "0xaabb11..." as string. For development and testing purpose on private or test net you can use the code below. Function hexStrToBytes will ...


22

Bytes is a dynamic array of bytes. It's shorthand for byte[] and you'll see examples of a bytes being treated as an array in code from time to time. myByte[x]. It can have a length of zero and you can do things like append a byte to the end. Bytes32 is exactly 32 bytes long. It takes exactly one 32-byte word to represent a bytes32 because there's no need ...


20

The alternative to @eth's answer is to use assembly: function toBytes(uint256 x) returns (bytes b) { b = new bytes(32); assembly { mstore(add(b, 32), x) } } This is significantly more gas-efficient, but depends on the internal memory layout used by the Solidity compiler. In theory, this can change in future, but in practice it should be fairly ...


18

To be even more efficient: function toBytes(address a) public pure returns (bytes memory b){ assembly { let m := mload(0x40) a := and(a, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) mstore(add(m, 20), xor(0x140000000000000000000000000000000000000000, a)) mstore(0x40, add(m, 52)) b := m } } Takes just 695 gas vs ...


14

Use "". contract MyContract{ bytes public data = "0x3333"; bytes public empty; function clearData(){ data = ""; } } Tested using https://ethereum.github.io/browser-solidity by looking at the value of data and empty.


9

Thanks to Piper and Chris I found a working solution for Solidity <= 0.2.1. The reason why the first two log statements return different results is, because uintN is right-aligned and bytesN is left-aligned. Conversion between uintN and bytesN first shortens and then changes alignment. That's why it has to be converted back to bytes32 before converted to ...


9

Whilst I have not worked with IPFS hashes, the solidity types documentation states that you can store fixed size byte arrays up to 32 bytes. As such if you want to store the whole hash in one data property you have to use the dynamic array type bytes. This is outlined here. If you want to store them separately, it seems perverse to me to implement the ...


8

Here's a comparison of the gas used in the three methods by @NickJohnson, @Eth and @k26dr. I've added a constant to the function modifiers as these functions do not alter the blockchain: pragma solidity ^0.4.2; contract Test { function toBytesNickJohnson(uint256 x) constant returns (bytes b) { b = new bytes(32); assembly { mstore(add(b, ...


8

Unlike some of the comments suggest, the unicorn symbol 🦄 (U+1F984) is located in the contract's symbol name. You can check this by running the following in a web3 browser's console: // taken from https://github.com/flyswatter/human-standard-token-abi/blob/master/index.js var tokenAbi = [ { "constant": true, "inputs": [], "name": "name", "...


8

The explanation is quite simple: In Solidity, bytes is a dynamically-sized byte array: Variables of type bytes and string are special arrays. A bytes is similar to byte[], but it is packed tightly in calldata. string is equal to bytes but does not allow length or index access (for now). In Solidity Assembly, variables are pointers to memory ...


7

Solidity <= 0.2.1 You can retrieve the nth byte of any bytesXX type with the following code. bytes32 v = ...; byte b = byte(bytes32(uint(v) * 2 ** (8 * n))); Solidity > 0.2.1 Starting in the next release of solidity you will be able to access them using indices. bytes32 v = ...; byte b = v[n];


7

The arguments are expressed as bytes, left-padded with zeroes to the maximum length of the data type you've passed in, and concatenated without any kind of delimiter. In Python, given two hex-encoded bytes32s prepended with a 0x called first and second, it looks something like: # keccak, change before upgrading pysha >= 3.10 from sha3 import sha3_256 ...


6

Here is my tiny one-liner for address to bytes32 conversion: bytes32(uint256(addr) << 96);


6

There are no current shortcuts and you need to write your own function. Here's the function suggested by Solidity's author, chriseth: function toBytes(address x) returns (bytes b) { b = new bytes(20); for (uint i = 0; i < 20; i++) b[i] = byte(uint8(uint(x) / (2**(8*(19 - i))))); }


6

The issue is that when you use a string literal like bytes public hardcodedCallData = "0x9461d6f7000000000000000000000000000000000000000000000000000000000000000a796f000000000000000000000000000000000000000000000000000000000000"; Solidity interprets the string as ASCII. In fact, if you do "...


6

It is possible to do this with assembly: pragma solidity ^0.4.8; contract c { event trace(bytes32 x, bytes16 a, bytes16 b); function foo(bytes32 source) { bytes16[2] memory y = [bytes16(0), 0]; assembly { mstore(y, source) mstore(add(y, 16), source) } trace(source, y[0], y[1]); } } For ...


6

This is going to take a few hops to explain. The code looks innocent enough, but there is a compiler warning about uninitialized storage pointers. The warning shouldn't be ignored. Written explicitly, it would be bytes storage first; Storage pointers can start to look like slight of hand. Consider this: MyStruct s = structsMap[key]; s.someVal = false;...


5

Your question is not clear enough. When you want to split 32 bytes into 5 variables that have a total length of 2+2+2+2+8+1 = 17 you should specify what bytes you want to be chunked (bytes from left or bytes from right). I wrote an example that solves your problem as far as I could understand it. Comment the answer - explain what you exactly need, and I'll ...


5

the \xNN notation is used to express hexadecimal like in Javascript(Hexadecimal escape sequences). The provided forms are the same to represent the value of :0xaca7da Difference : \x could be used to express a special hex(initial form) value within a string e.g : "aca7\xd4" which is in asci will be converted to hex 0x61636137da so 'da' keeps its form(not ...


5

I am proposing using bytesN instead string: pragma solidity ^0.4.6; contract C { struct User { uint balance; } mapping (bytes24 => User) public accounts; function newUser(bytes24 id, uint balance) { accounts[id] = User(balance); } } you could also convert bytes to string look at : How to convert a bytes32 to string


5

Here are some js functions for stripping and re-adding the first two bytes containing the hash function and size, suitable for web3. import bs58 from 'bs58' // Return bytes32 hex string from base58 encoded ipfs hash, // stripping leading 2 bytes from 34 byte IPFS hash // Assume IPFS defaults: function:0x12=sha2, size:0x20=256 bits // E.g. "...


5

The ABI encoding includes an offset to the start of data. The first 0x20 is the offset to the start of data as described in this example: https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI#use-of-dynamic-types In the example look at: 0x0000000000000000000000000000000000000000000000000000000000000080 (offset to start of data part of second ...


4

Here is an one-line solution. abi.encodePacked(addr) It's simple and costs little


4

EDIT: See How to pass arbitrary bytes to a function in Remix The behavior in Remix was changed so see above; the following was for an older version of Remix / browser-solidity. To pass bytes to a function, pass the bytes as a hex string. Example in Solidity Browser: contract SimpleStorage { bytes storedData; function set(bytes x) { ...


4

contract C1 { function f1() returns(bytes) { bytes memory bb = "\x00\x01\x02"; // you can extend this return(bb); } } Tested using online Solidity Browser, output is: Result: "...


4

There are no easy ways to convert anything to bytes. Here's a function: function toBytes(uint256 x) returns (bytes b) { b = new bytes(32); for (uint i = 0; i < 32; i++) { b[i] = byte(uint8(x / (2**(8*(31 - i))))); } } Based on Solidity Gitter chat.


4

There is a general difference between logical and bitwise operators, logical operators can only be applied to booleans and bitwise operators can only be applied to "bitfields" like bytes32. Of course the concept of "logical exclusive disjunction" exists, but there is no actual operator by that name. Having said that, a != b should do the trick.


4

You can do something like this. Note, for every custom struct you'll have to write custom serialization and deserialization methods. pragma solidity ^0.4.0; contract StructSerialization { function StructSerialization() { } event exactUserStructEvent(uint32 id, string name); //Use only fixed size simple (uint,int) types! struct ...


4

The author of the github page that you referenced didn't update the free memory pointer after allocating the memory. Also as Tjaden Hess noted in the comments return as an opcode and return as a Solidity statement are very different. The opcode causes the entire contract execution to return at that point, with the return value that you designate in ...


Only top voted, non community-wiki answers of a minimum length are eligible