30

I have a contract with a public variable that's bytes32. If I enter the value 20160528 then it auto converts to bytes32. Is there anyway to convert it back from the nodejs terminal? I've been trying

web3.toAscii(testInstance.Date.call()) 

but it just gives me nonsense. Here is the the test code:

contract test {
  bytes32 public Date;

  function test(bytes32 _date){
      Date=_date; 
  }
}
1
  • Convert back to 20160528 ?
    – Gawey
    Commented Jul 26, 2017 at 6:58

1 Answer 1

46

For web3 0.x:

You need to use web3.fromAscii(val) to write correct bytes32 input to contract.

And you are right, anyone can read it with web3.toAscii(val).

Full web3.js code in terms of your designations:

//sets bytes32
testInstance.test.sendTransaction(web3.fromAscii("20160528"), options);

//gets bytes32
testInstance.Date.call(function(err, val) {
    if  (err) console.log(err);
    console.log(web3.toAscii(val));
    // will print "20160528"
 });

For web3 1.0:

Note: fromAscii has been deprecated

You need to use web3.utils.asciiToHex(val) to write correct bytes32 input to contract.

And you are right, anyone can read it with web3.utils.hexToAscii(val).

Full web3.js code in terms of your designations:

//sets bytes32
testInstance.methods.test(web3.utils.asciiToHex("20160528")).send(options);

//gets bytes32
testInstance.methods.Date().call(function(err, val) {
    if  (err) console.log(err);
    console.log(web3.utils.hexToAscii(val));
    // will print "20160528"
 });
7
  • 2
    I'm getting an error Uncaught (in promise) TypeError: hex.substring is not a function when trying to log val, which seems to be a complex object. Have things changed in web3 recently?
    – Stan James
    Commented Oct 5, 2017 at 23:59
  • 2
    @StanJames I've updated my answer with the code for web3 1.0. Previous one was for web 0.x Commented Oct 6, 2017 at 16:36
  • 1
    How to deal with trailing zeroes? Commented May 19, 2019 at 15:46
  • 3
    I'm getting Error: incorrect data length Does this method also make the bytes32 the right length somehow? Commented Mar 23, 2021 at 0:12
  • 1
    @PatrickCollins I'm getting the same. Did you find a fix?
    – Alex C
    Commented Apr 11, 2021 at 16:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.