Solidity
如何將 byte32 數組的元素轉換為數字?
該數組包含一個 SHA256 雜湊。我想將 2 個十六進制值相加,然後將它們乘以 1.125(只保留整數)。結果數字將代表一個字母數字字元,它將是隨機的。
“0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ”(長度為36)
所以我想從這個字元串中選擇隨機字母,我擁有的是一個 SHA256 雜湊。
function GenerateSixDigitCode() private view returns (bytes32) { uint8[6] TwoHashDigit; //We add up 2 hex digit, than multiply it by 1.125 (32 to 36 conversion) //The CryptoZombies tutorial mentioned that this is not the best source of randomness, but in some cases this is sufficient. //This will be a ticket buying app just for learning purposes so it should be good enough bytes32 seed = (keccak256(abi.encodePacked( block.timestamp + block.difficulty + ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)) + block.gaslimit + ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)) + block.number ))); //The user should get a 6-digit code, like this: X4C9BA //I'm trying to generate the 6-digit code from sha256 TwoHashDigit[0] = (seed[0] + seed[1]) * 1.125; TwoHashDigit[1] = (seed[2] + seed[3]) * 1.125; TwoHashDigit[2] = (seed[4] + seed[5]) * 1.125; TwoHashDigit[3] = (seed[6] + seed[7]) * 1.125; TwoHashDigit[4] = (seed[8] + seed[9]) * 1.125; TwoHashDigit[5] = (seed[10] + seed[11]) * 1.125; //TwoHashDigit should contain random numbers now, in the range of 0-36 //Later I would map numbers to alphanumeric characters, using this string alpha = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" //For example alpha[10] == 'A' //alpha[20] == 'K' }
我得到的錯誤:
contracts/ticketpurchaser.sol:43:27: TypeError: Operator * not compatible with types bytes1 and rational_const 9 / 8 TwoHashDigit[5] = (seed[10] + seed[11]) * 1.125;
更改每次出現的情況:
(seed[x] + seed[y]) * 1.125
對此:
uint8((uint16(seed[x]) + uint16(seed[y])) * 9 / 8)
既然你有很多,你也可以在一個函式中實現它:
function combine(bytes1 x, bytes1 y) private pure returns (uint8) { return uint8((uint16(x) + uint16(y)) * 9 / 8); }