【2022 元宇宙基础NFT之Solidity OOP编程第16篇】3分钟了解Solidity Types – Dynamically-sized byte array
一、Dynamically-sized byte array
string
是一个动态尺寸的UTF-8
编码字符串,它其实是一个特殊的可变字节数组,string
是引用类型,而非值类型。bytes
动态字节数组,引用类型。
根据经验,在我们不确定字节数据大小的情况下,我们可以使用string
或者bytes
,而如果我们清楚的知道或者能够将字节数控制在bytes1
~ bytes32
,那么我们就使用bytes1
~ bytes32
,这样的话能够降低存储成本。
二、常规字符串 sting 转换为 bytes
string
字符串中没有提供length
方法获取字符串长度,也没有提供方法修改某个索引的字节码,不过我们可以将string
转换为bytes
,再调用length
方法获取字节长度,当然可以修改某个索引的字节码。
1、源码
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract C {
bytes9 public g = 0x6c697975656368756e;
string public name = "liyuechun";
function gByteLength() view public returns (uint) {
return g.length;
}
function nameBytes() view public returns (bytes memory) {
return bytes(name);
}
function nameLength() view public returns (uint) {
return bytes(name).length;
}
function setNameFirstByteForL(bytes1 z) public {
// 0x4c => "L"
bytes(name)[0] = z;
}
}
2、说明
function nameBytes() view public returns (bytes memory) {
return bytes(name);
}
nameBytes
这个函数的功能是将字符串name
转换为bytes
,并且返回的结果为0x6c697975656368756e
。0x6c697975656368756e
一共为9字节
,也就是一个英文字母对应一个字节。
function nameLength() view public returns (uint) {
return bytes(name).length;
}
我们之前讲过,string
字符串它并不提供length
方法帮助我们返回字符串的长度,所以在nameLength
方法中,我们将name
转换为bytes
,然后再调用length
方法来返回字节数,因为一个字节对应一个英文字母,所以返回的字节数量刚好等于字符串的长度。
function setNameFirstByteForL(bytes1 z) {
// 0x4c => "L"
bytes(name)[0] = z;
}
如果我们想将name
字符串中的某个字母进行修改,那么我们直接通过x[k] = z
的形式进行修改即可。x
是bytes类型的字节数组,k
是索引,z
是bytes1
类型的变量值。
setNameFirstByteForL
方法中,我就将liyuechun
中的首字母修改成L
,我传入的z
的值为0x4c
,即大写的L
。
三、汉字字符串或特殊字符的字符串转换为bytes
1、特殊字符
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract C {
string public name = "a!+&520";
function nameBytes() view public returns (bytes memory) {
return bytes(name);
}
function nameLength() view public returns (uint) {
return bytes(name).length;
}
}
在这个案例中,我们声明了一个name
字符串,值为a!+&520
,根据nameBytes
和nameLength
返回的结果中,我们不难看出,不管是字母
、数字
还是特殊符号
,每个字母对应一个byte(字节)
。
2、中文字符串
0.7.0
以前的版本支持中文字符串,如下所示。
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0 <0.7.0;
contract C {
string public name = "黎跃春";
function nameBytes() view public returns (bytes memory) {
return bytes(name);
}
function nameLength() view public returns (uint) {
return bytes(name).length;
}
}
在上面的代码中,我们不难看出,黎跃春
转换为bytes
以后的内容为0xe9bb8ee8b783e698a5
,一共9个字节
。也就是一个汉字需要通过3个字节
来进行存储。那么问题来了,以后我们取字符串时,字符串中最好不要带汉字,否则计算字符串长度时还得特殊处理。
-
0.7.0
后面的版本已经不支持中文字符串了,给string
赋值中文字符串时,会报错,如下所示:
四、bytes字节数组
或者

验证码: