[Ethereum] How to convert Java String to Bytes32 in Java ? I am using web3j solidity wrapper to interact with Smart contract. I am getting following error:

ethereumjjavaweb3j

java.lang.UnsupportedOperationException: Input byte array must be in range 0 < M <= 32 and length must match type

I am trying to do as given below. I wanted to add the people but wrapper generated in web3j throwing the error above:

String s = "Rahul"; 
//System.out.println(s.getBytes().length);
Bytes32 b1=new Bytes32(s.getBytes());
contract.addPerson(b1,new Uint256(new BigInteger("35"));

Best Answer

It is best to use the JVM runtime library whenever possible; that code is usually of high quality, although exceptions do exist. In the following code I first create a byte[], then derive a hex value by calling DatatypeConverter.printHexBinary.

byte[] byteArray = "This string is converted to a byte array".getBytes();
String hexValue = javax.xml.bind.DatatypeConverter.printHexBinary(byteArray);
Related Topic