I am new to Solidity, so please, accept my apologies, if the question is really dumb. I am trying to write two functions, one of which gets the uint256 and converts it to a binary number, and the other gets the binary input (if that's even possible) and returns a uint256. Is such a conversion even possible?
I still can't imagine a use for this, but I wrote code to do it because it seemed fun:
pragma solidity ^0.4.19;
contract Convert {
function toBinaryString(uint8 n) public pure returns (string) {
// revert on out of range input
require(n < 32);
bytes memory output = new bytes(5);
for (uint8 i = 0; i < 5; i++) {
output[4 - i] = (n % 2 == 1) ? byte("1") : byte("0");
n /= 2;
}
return string(output);
}
function fromBinaryString(bytes5 input) public pure returns (uint8) {
uint8 n = 0;
for (uint8 i = 0; i < 5; i++) {
n *= 2;
if (input[i] == "1") {
n += 1;
} else {
// revert on malformed input
require(input[i] == "0");
}
}
return n;
}
}
-
The reason would be, if you have a set numbers representing different flag states, such as 1, 2, 4,, 8, 16, and you wanted to identify which ones were in your sample number, the simple way would be to Xor your number. but alas you can not do that with an integer. – Cyberience Mar 27 '19 at 3:34
-
I'm not sure what you're saying. You can certainly
xor
two integers in Solidity. (Although in the case of checking for flags, don't you wantand
? E.g.if (flags & 1) ...
,if (flags & 2) ...
) – user19510 Mar 27 '19 at 3:36 -
I am working on something similar and tried your suggestion before you replied, and using solidity 0.5.0 in remix I get the TypeError: Type uint8 is not implicitly convertible to expected type bool. if (_restrictionCode & 8) { – Cyberience Mar 27 '19 at 3:48
-
1
bytes16
is a sequence of 16 bytes of data. Those bytes can be anything and can be interpreted any way. (You could use it to store a number of a string.) Maybe you can give an example of the input and the output you want or further explain what you're trying to accomplish. – user19510 Feb 13 '18 at 4:14x = 7
involves binary in the CPU, but why do you care?) – user19510 Feb 13 '18 at 4:15