Skip to content

Instantly share code, notes, and snippets.

@fassko
Created November 22, 2022 17:56
Embed
What would you like to do?
Created using remix-ide: Realtime Ethereum Contract Compiler and Runtime. Load this file by pasting this gists URL or ID at https://remix.ethereum.org/#version=soljson-v0.8.7+commit.e28d00a7.js&optimize=false&runs=200&gist=
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "hardhat/console.sol";
library String {
function convertToBytes(string memory self) public pure returns (bytes memory result) {
bytes memory stringBytes = bytes(self);
return stringBytes;
}
function convertToBytes32(string memory self) public pure returns (bytes32 result) {
bytes memory tempEmptyStringTest = bytes(self);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
result := mload(add(self, 32))
}
}
}
contract SolidityBytes {
using String for string;
bytes _dynamicBytesStorage = new bytes(200);
function convertToBytes(string memory input) external pure returns(bytes memory) {
return input.convertToBytes();
}
function convertToBytes32(string memory input) external pure returns(bytes32) {
return input.convertToBytes32();
}
function convertToString(bytes memory input) external pure returns(string memory) {
return string(input);
}
function fixedBytesOne() external pure returns(bytes1) {
// bytes1 b1 = hex"41";
bytes1 b1 = 0x41;
return b1;
}
function fixedBytes32() external pure returns(bytes32) {
bytes32 b32 = hex"41";
return b32;
}
function dynamicBytesStorage() external returns(bytes memory) {
_dynamicBytesStorage.push(hex"41");
console.log(string(_dynamicBytesStorage));
return _dynamicBytesStorage;
}
function dynamicBytesMemory() external view returns(bytes memory) {
bytes memory _dynamicBytesMemory = hex"41";
console.log(string(_dynamicBytesMemory));
return _dynamicBytesMemory;
}
function dynamicBytesMemoryNew() external view returns(bytes memory) {
bytes memory _dynamicBytesMemoryNew = new bytes(200);
_dynamicBytesMemoryNew[0] = hex"41";
console.log(string(_dynamicBytesMemoryNew));
return _dynamicBytesMemoryNew;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment