简体   繁体   English

将字符串转换为bytes32以用于实体合约调用

[英]Converting string to bytes32 to be used in solidity contract call

How can I convert a Perl string to bytes32 like the java function below: 我如何将Perl字符串转换为bytes32,例如以下Java函数:

public static Bytes32 stringToBytes32(String string) {
    byte[] byteValue = string.getBytes();
    byte[] byteValueLen32 = new byte[32];
    System.arraycopy(byteValue, 0, byteValueLen32, 0, byteValue.length);
    return new Bytes32(byteValueLen32);
}

Is there any module available in CPAN to do this? CPAN中有可用的模块来执行此操作吗?

It looks like all this function does it to encode a string into bytes, then truncate/pad it so the result is exactly 32 bytes long. 看起来所有这些功能都将字符串编码为字节,然后截断/填充它,因此结果恰好是32个字节长。

The first part may be tricky because according to the documentation : 第一部分可能很棘手,因为根据文档

 public byte[] getBytes() 

Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array. 使用平台的默认字符集将此String编码为字节序列,并将结果存储到新的字节数组中。

The behavior of this method when this string cannot be encoded in the default charset is unspecified. 未指定无法在默认字符集中编码此字符串时此方法的行为。

Perl doesn't really have a concept of a "default charset", but if you're willing to settle for UTF-8, it's not hard: Perl实际上没有“默认字符集”的概念,但是如果您愿意接受UTF-8,这并不难:

sub stringToBytes32 {
    my ($str) = @_;
    utf8::encode $str;
    return pack 'a32', $str;
}

(See Encode::encode if you need a different encoding.) (如果需要其他编码,请参见Encode::encode 。)

pack is handy for producing data in binary formats. pack方便用于生成二进制格式的数据。 Here we use it to truncate/pad to 32 bytes. 在这里,我们使用它来截断/填充到32个字节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM