一、动态大小字节数组
string
是一个动态尺寸的UTF-8
编码字符串,它其实是一个特殊的可变字节数组,string
是引用类型,而非值类型。bytes
动态字节数组,引用类型。
根据经验,在我们不确定字节数据大小的情况下,我们可以使用string
或者bytes
,而如果我们清楚的知道或者能够将字节数控制在bytes1
~ bytes32
,那么我们就使用bytes1
~ bytes32
,这样的话能够降低存储成本。
二、常规字符串 string 转换为 bytes
string
字符串中没有提供length
方法获取字符串长度,也没有提供方法修改某个索引的字节码,不过我们可以将string
转换为bytes
,再调用length
方法获取字节长度,当然可以修改某个索引的字节码(等同于:想要获取一个string的长度,必须转为bytes;想要修改string的内容,必须转换为bytes)。
1、源码
pragma solidity ^0.4.4;
contract C {
bytes9 public g = 0x6c697975656368756e;
string public name = "liyuechun";
function gByteLength() constant returns (uint) {
return g.length;
}
function nameBytes() constant returns (bytes) {
return bytes(name);
}
function nameLength() constant returns (uint) {
retur