I am having trouble doing some string comparison against the last 2 digits of a block hash in solidity. I'm also a little bit confused about how to work with a single character, as it appears that a single byte in solidity contains 2 characters.
I grab a blockhash:
bytes32 myHash = block.blockhash(block.number - 1);
And I get something like:
"0x18676e992055c057538d59b378271bb4eacdb7f6abf9e815fd63255dc11166b6"
I attempt to grab the last character by doing:
byte x = myHash[31];
This gives me a value like this, when printed in a log:
"b600000000000000000000000000000000000000000000000000000000000000"
This is where I'm confused. This is the last 2 characters of the bytes32. I want to use the following function to determine the hex integer value of the character:
function getCoordinate(byte val) returns(uint) {
if (val == "0") {
return 0;
} else if (val == "1") {
return 1;
} else if (val == "2") {
return 2;
} else if (val == "3") {
return 3;
} else if (val == "4") {
return 4;
} else if (val == "5") {
return 5;
} else if (val == "6") {
return 6;
} else if (val == "7") {
return 7;
} else if (val == "8") {
return 8;
} else if (val == "9") {
return 9;
} else if (val == "a") {
return 10;
} else if (val == "b") {
return 11;
} else if (val == "c") {
return 12;
} else if (val == "d") {
return 13;
} else if (val == "e") {
return 14;
} else if (val == "f") {
return 15;
}
}
However, none of the cases match, so it always returns 0. Anyone have any knowledge of how to get a single character so that this function will work properly?
Best Answer
Since every byte is encoded as 2 hexadecimal characters (e.g. in your example the last byte is 0xb6) you need 2 functions: one for the left coordinate, another for the right coordinate:
15
is the decimal representation of the binary 00001111. Bitwise&
with it gives you the right coordinate.>> 4
shifts the first 4 bits to the right discarding the other 4 bits.