I am trying to take user input strings and convert them to bytes32
and bytes5
for a contract built in Solidity 5.11, I tried 32 and 5 character long random strings respectively however they are not working, is there an inbuilt function for web3 to convert Strings to bytes (either 32 or 5) like web3.utils.fromAscii
can be used to generate appropriate addresses from strings?
console.log(addressing("address");
console.log(bitify32("data"));
console.log(bitify5("key"));
function addressing(input) {
let zeros = "0";
let input = web3.utils.fromAscii(input);
if (input.length < 42) {
let remainder = 32-input.length;
for(let i = remainder-1; i > 0; i--) {
zeros += "0";
}
}
let inputZerod = input+zeros;
return inputZerod;
}
function bytify32(input) {
let zeros = "0";
let input = web3.utils.fromAscii(input);
if (input.length < 32) {
let remainder = 32-input.length;
for(let i = remainder-1; i > 0; i--) {
zeros += "0";
}
}
let inputZerod = input+zeros;
return inputZerod;
}
pragma solidity ^0.5.11;
contract bytesTest{
mapping(address => BytesStruct) testBytes;
struct BytesStruct{
address stringAddress;
bytes32 string1;
bytes5 string2;
}
function getByteStrings(address _stringAddress) view public returns(bytes32, bytes5){
return(testBytes[_stringAddress].string1, testBytes[_stringAddress].string2);
}
function addByteString(address _stringAddress, bytes32 _string1, bytes5 _string2) public{
testBytes[_stringAddress].string1 = _string1;
testBytes[_stringAddress].string2 = _string2;
}
}
web3.utils.fromAscii(input)
(or in its more common name -web3.utils.asciiToHex(input)
), which you are already using. Why all the padding?bytes32
doesn't make an address out of it in any way. An address is 20 bytes, not 32!