bytes32到javascript中的字符串

rah*_* mr 4 javascript string hex ethereum solidity

目前我正在研究一个以太坊dapp(投票),在我的智能合约中,我有一个函数来获取类型bytes32 []的候选列表,在java脚本方面我没有得到值而不是0x仅如何解析值,下面是代码

pragma solidity ^0.4.0;


contract Voting {


  mapping (bytes32 => uint8) public votesReceived;



  bytes32[] public candidateList;
string myString = "someString";



  function Voting(bytes32[] candidateNames) public {
    candidateList = candidateNames ;

  }


  function totalVotesFor(bytes32 candidate) view public returns (uint8) {
    return votesReceived[candidate];
  }

  function addCandidate(bytes32 candidate)  public returns (bool){
    require(isNewEntry(candidate));
    candidateList.push(candidate);
    return isNewEntry(candidate);
  }

  function voteForCandidate(bytes32 candidate) public {
    require(validCandidate(candidate));
    votesReceived[candidate] += 1;
  }

  function getCandidateList() view public returns (bytes32[]) {
return candidateList;
  }

  function isNewEntry(bytes32 candidate) view public returns (bool) {
    for(uint i = 0; i < candidateList.length; i++) {
        if (candidateList[i] == candidate) {
            return false;
        }
    }
    return true;
  }

  function validCandidate(bytes32 candidate) view public returns (bool) {
    for(uint i = 0; i < candidateList.length; i++) {
      if (candidateList[i] == candidate) {
        return true;
      }
    }
    return false;
  }
}
Run Code Online (Sandbox Code Playgroud)

下面是访问合同函数的代码

Voting.deployed().then(function(contractInstance) {
    contractInstance.getCandidateList.call().then(function(v) {
    console.log(v)
    });
  })
Run Code Online (Sandbox Code Playgroud)

有人请帮助我

Mic*_*ohl 12

假设你在web3JS方面使用它,那就是web3.toAscii.

来自文档的示例:

var str = web3.toAscii("0x657468657265756d000000000000000000000000000000000000000000000000");
console.log(str); // "ethereum"
Run Code Online (Sandbox Code Playgroud)

  • 在当前版本的web3中,您应该调用`web3Provider.utils.toAscii()` (5认同)