Ich versuche, Hex-String in Bytes umzuwandeln.
function MyContract() public {
string memory str = "A76A95918C39eE40d4a43CFAF19C35050E32E271";
array1 = bytes(str);
bytes memory str1 = hex"A76A95918C39eE40d4a43CFAF19C35050E32E271";
array2 = str1;
}
In array1 habe ich nur Unicode von str like array1[0] - 41
. In Array 2 habe ich, was ich will array2[0] - a7
. Aber ich kann Hex nicht mit Variablen verwenden.
Ich möchte Funktionsargumente für die Konvertierung in Bytes verwenden wie:
function (string str) {
return bytes(hex(str))
}
Frage: Gibt es eine Möglichkeit, die Konvertierung in Solidity durchzuführen?
Vielen Dank im Voraus.
Dies ist sehr ineffizient, sollte aber funktionieren
// Convert an hexadecimal character to their value
function fromHexChar(uint8 c) public pure returns (uint8) {
if (bytes1(c) >= bytes1('0') && bytes1(c) <= bytes1('9')) {
return c - uint8(bytes1('0'));
}
if (bytes1(c) >= bytes1('a') && bytes1(c) <= bytes1('f')) {
return 10 + c - uint8(bytes1('a'));
}
if (bytes1(c) >= bytes1('A') && bytes1(c) <= bytes1('F')) {
return 10 + c - uint8(bytes1('A'));
}
revert("fail");
}
// Convert an hexadecimal string to raw bytes
function fromHex(string memory s) public pure returns (bytes memory) {
bytes memory ss = bytes(s);
require(ss.length%2 == 0); // length must be even
bytes memory r = new bytes(ss.length/2);
for (uint i=0; i<ss.length/2; ++i) {
r[i] = bytes1(fromHexChar(uint8(ss[2*i])) * 16 +
fromHexChar(uint8(ss[2*i+1])));
}
return r;
}
In jedem Fall würde ich empfehlen, zu versuchen, Ihre hexadezimalen Daten außerhalb der Solidität zu konvertieren.
das Fett
Ismael
bytes32 r
stattbytes memory r = new bytes(..)
. Das Problem ist, dass es nicht einfach ist, einzelne Bytes von bytes32 zu ändern, aber das Umwandeln in uint und die Verwendung von Verschiebungen können Sie erreichen.Jim
Ismael
Jim
Ismael
Jim
Ismael
Jim