[英]How to use BytesToUint function in Solidity (the one with assembly)?
我正在使用以下 function 將字節轉換為 uint:
function bytesToUint(bytes b) public pure returns (uint){
uint number;
for(uint i=0;i<b.length;i++){
number = number + uint(b[b.length-1-i])*(10**i);
}
return number;
}
由於不再支持顯式 byte1 到 uint 的轉換,我找到了以下替代方法:
function toUint256(bytes memory _bytes, uint256 _start) internal pure returns (uint256) {
require(_bytes.length >= (_start + 32), "Read out of bounds");
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
字節是 ERC20 Token 的 ApproveAndCall function 中的輸入
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
它被發送到我的智能合約的receiveApproval。
function receiveApproval(address _from, uint _token, address _tokenContract, bytes memory _data) public {
if(!ERC20Interface(_tokenContract).transferFrom(_from, address(this), _token)) {
revert();
}
_0xChangeLib.place_sell_order(exchange, _from, _tokenContract, _token, _0xChangeLib.toUint256(_data, 0));
}
有人能解釋一下這個新的 BytesToUint256 是如何工作的嗎? 我無法理解匯編代碼以及如何使用這個 function。 我不明白 uint256 _start 參數。 我也不確定是否可以使用與輸入相同的格式。 作為參數,我將 wei 數量轉換為字節,例如 100 wei = 0x100,在 javascript 中使用簡單的 function 並使用 Web3.js 發送到令牌地址。
我想在智能合約的 ReceiveApproval function 中調用 BytesToUint function 來進一步處理數據。
非常感謝您的幫助!
_start
基本上指向bytes
數組中 integer 值開始的字節索引。 前 32 個(或十六進制的 0x20)字節包含bytes
數組的長度,然后開始存儲在接下來的 32 個字節中的 integer 值。 _start 值為零,因為第二組 32 個字節包含您需要的 integer 值。 您基本上可以將此 function 轉換為此。
function toUint256(bytes memory _bytes)
internal
pure
returns (uint256 value) {
assembly {
value := mload(add(_bytes, 0x20))
}
}
關於您的評論, 0x0
表示字節數組的長度為 1,即第二個零,並且require
語句預計長度至少為 32。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.