固定大小字節數組
pragma solidity ^0.4.5;
contract pcl {
bytes1 _name1;
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';
bytes public bname=new bytes(5);
function getname(bytes1 a) {
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;
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) {
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);
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) {
return string(_bname);
}
function zhuanhuan_1() constant returns (string){
for (uint i;i<name.length;i++){
_bname[i]=name[i];
}
return string(_bname);
}
}
黎老師的通用固定字節數組轉string函數就不學了。大概意思瞭解下。
byte 相當於byte1
會返回字節數組中的最後一個字節。
通過不斷左移固定大小字節長度個單位(8*n因爲左移針對二進制),遍歷數組,判斷是否爲0,不爲0就添加到動態字節數組中進行代轉換。
至於byte和uint左移相同次數爲什麼得到不同。我、、不知道(*╹▽╹*)。