Ich weiß bereits, wie man bytes32ToString und stringToBytes32 konvertiert:
function bytes32ToString(bytes32 x)
public
pure
returns (string memory)
{
bytes memory bytesString = new bytes(32);
uint charCount = 0;
uint j = 0;
for (j = 0; j < 32; j++) {
byte char = byte(bytes32(uint(x) * 2 ** (8 * j)));
if (char != 0) {
bytesString[charCount] = char;
charCount++;
}
}
bytes memory bytesStringTrimmed = new bytes(charCount);
for (j = 0; j < charCount; j++) {
bytesStringTrimmed[j] = bytesString[j];
}
return string(bytesStringTrimmed);
}
function stringToBytes32(string memory source)
public
pure
returns (bytes32 result)
{
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
result := mload(add(source, 32))
}
}
Aber wie konvertiert man eine Zeichenfolge in Bytes256 oder beliebige Bytes? oder beliebige Bytes in String umwandeln?
Selber gelöst...
function substring(string memory str, uint startIndex, uint endIndex)
public
pure
returns (string memory)
{
bytes memory strBytes = bytes(str);
bytes memory result = new bytes(endIndex-startIndex);
for(uint i = startIndex; i < endIndex; i++) {
result[i-startIndex] = strBytes[i];
}
return string(result);
}
function stringToBytes256(string memory source)
public
pure
returns (byte[256] memory result)
{
uint length = bytes(source).length;
for(uint i=0;i<length/32;i++){
bytes32 b32 = stringToBytes32(substring(source, i*8, i*8+32));
for(uint j=0;j<32;j++){
result[i*32+j] = b32[j];
}
}
bytes32 b32 = stringToBytes32(substring(source, length/32*32, length));
uint i=0;
for(uint k=length/32*32; k<length; k++){
result[k] = b32[i];
i++;
}
}
function bytes256ToString(byte[256] memory x) public pure returns (string memory) {
bytes memory bytesString = new bytes(256);
uint charCount = 0;
for (uint j = 0; j < 256; j++) {
byte char = x[j];
if (char != 0) {
bytesString[charCount] = char;
charCount++;
}
}
bytes memory bytesStringTrimmed = new bytes(charCount);
for (uint j = 0; j < charCount; j++) {
bytesStringTrimmed[j] = bytesString[j];
}
return string(bytesStringTrimmed);
}
public class byteString {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
String msg = "Hello";
byte[] buff = new byte[1024];
buff = msg.getBytes("UTF-8");
System.out.println(buff);
String m = new String(buff);
System.out.println(m);
}
}
Benutzer19510
bytes256
. Aber Sie können tunbytes(s)
, um astring
in abytes
oder a in asstring(b)
umzuwandeln .bytes
string