Intento convertir una cadena hexadecimal a bytes.
function MyContract() public {
string memory str = "A76A95918C39eE40d4a43CFAF19C35050E32E271";
array1 = bytes(str);
bytes memory str1 = hex"A76A95918C39eE40d4a43CFAF19C35050E32E271";
array2 = str1;
}
En array1 solo tengo unicode de str como array1[0] - 41
. En la matriz 2 tengo lo que quiero array2[0] - a7
. Pero no puedo usar hexadecimal con variable.
Quiero usar argumentos de función para la conversión a bytes como:
function (string str) {
return bytes(hex(str))
}
Pregunta: ¿Hay alguna forma de hacer la conversión en Solidity?
Muchas gracias de antemano.
Esto es muy ineficiente pero debería funcionar.
// 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;
}
En cualquier caso, recomendaría intentar convertir sus datos hexadecimales fuera de la solidez.
el feto
ismael
bytes32 r
en lugar debytes memory r = new bytes(..)
. El problema es que no es fácil modificar bytes individuales de bytes32, pero puede lograrlo con la conversión a uint y el uso de turnos.Jim
ismael
Jim
ismael
Jim
ismael
Jim