以太坊學習第三天

固定大小字節數組

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左移相同次數爲什麼得到不同。我、、不知道(*╹▽╹*)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章