以太坊学习第三天

固定大小字节数组

pragma solidity ^0.4.5;

contract pcl {
    bytes1 _name1;      //固定大小字节数组通过bytes1-bytes32来声明,byte就相当于bytes1
    bytes3 _name3;
    
    function pcl() {
        _name1=0x1f;
        _name3=0x1f2b3c;
    }
    
    function getpcl() constant returns (bytes3){
        return ~_name3<<2;
    }
    
    function suoying() constant returns (bytes1){
        return _name3[1];
    }
    
    function changdu() constant returns (uint){
        return _name3.length;   
    }
}

动态大小字节数组的声明、更改、清空、push

pragma solidity ^0.4.5;

contract pcl {
    string public name='aaaaa';        //string是一个特殊的动态大小字节数组。他没有length方法,也不能使用索引更改,但是可以通过bytes函数转化成bytes动态字节数组去操作。
    //这里我发现这种动态数组并不能通过bytes转换直接对他的length进行清空。(好吧可以,我没有取消constant的modifi)
    bytes public bname=new bytes(5);  //动态长度数组是可以通过new bytes来声明。 后面应该会学到定长数组转动态数组再转string。

    function getname(bytes1 a) {        //我的天啊,为什么要通过索引,这样还要转换成bytes去更改。就为了省一点gas费吗。
        bytes(name)[0]=a;
    }
    
    function getlenght() constant returns (uint256){
        return bytes(name).length;
    }

    function clear(uint len){
        bname.length=len;
    }

    function getNameLength(bytes1 ta){
        bytes(name)[0]=ta;
    }

    function pushTest(bytes1 a) {
        bname.push(a);
    }
}

固定大小字节数组之间转换的丢失

pragma solidity ^0.4.5;

contract pcl {
    bytes3 public _bname1=0xa1;   //但是刚定义的时候如果占用的比较少, 就在前面添0  比如这里是0x0000a1.就像使用bytes1转换过一样。因为0xa1本来就只占用1个字节。
    bytes2 public _bname=0xa1b1;

    function pcl(bytes2 name) {
        _bname=name;
    }

    function  zhuanhuan_1() constant returns (bytes1){   //当转小了,就从后面截取
        return bytes1(_bname);
    }

    function zhuanhuan_3() constant returns(bytes3) {    //当转大了,就在后面添0
        return bytes3(_bname);
    }
}

固定字节数组转动态字节数组

pragma solidity ^0.4.5;

contract pcl {
    bytes3 public _bname=0x1a2b3c;

    function zhuanhuan_1() constant returns (bytes){
        bytes memory t=new bytes(3);        //这里我暂且理解为t不需要一直存储到区块链中,所以声明为memory。但是为什么不能强制转换为storage后面看能不能解答。**Mark**
        for (uint i=0;i<_bname.length;i++){
            t[i]=_bname[i];
        }
        return t;
    }
}

动态大小字节数组转string

pragma solidity ^0.4.5;

contract pcl {
    bytes public _bname=new bytes(1);
    bytes3 public name=0xe892b2;
    
    function pcl(){
        _bname='蒲';
    }
    function zhuanhuan() constant returns (string) {        //动态大小字节数组可以通过string直接转换
        return string(_bname);
    }
    
    function zhuanhuan_1() constant returns (string){       //静态的可通过先转动态再string
        for (uint i;i<name.length;i++){
            _bname[i]=name[i];
        }
        return string(_bname);
    }
}
黎老师的通用固定字节数组转string函数就不学了。大概意思了解下。
byte 相当于byte1  
会返回字节数组中的最后一个字节。
通过不断左移固定大小字节长度个单位(8*n因为左移针对二进制),遍历数组,判断是否为0,不为0就添加到动态字节数组中进行代转换。
至于byte和uint左移相同次数为什么得到不同。我、、不知道(*╹▽╹*)
发布了3 篇原创文章 · 获赞 1 · 访问量 489

猜你喜欢

转载自blog.csdn.net/xiaoyue2019/article/details/105335911
今日推荐