固定大小字节数组
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左移相同次数为什么得到不同。我、、不知道(*╹▽╹*)。