|
本帖最后由 QAQ 于 2019-4-13 08:54 编辑
- <?php
- /*
- 本程序仅限64位PHP7以上版本使用,不支持32位
- 8位地址:0~7 16位地址:0~3 32位地址:0~1 64位无地址
- 8~32位值范围:0~ 2的位数次方-1
- 64位值范围:PHP_INT_MIN ~ PHP_INT_MAX
- */
- class union64{ //64位联合体(8字节)
- var $value = array(0,0,0,0,0,0,0,0);
- var $bas = 0;
- //Union读数值程序 参数a:地址 (64位无地址)
- function r8($a){
- $a &=7;
- $a = $this->bas ? $a : $a^7;
- return $this->value[$a];
- }
- function r16($a){
- $a &=3;
- $h = $a << 1;
- $l = $h + 1;
- $r = 0;
- $r = $this->r8($h)<<8;
- $r |= $this->r8($l);
- return $r;
- }
-
- function r32($a){
- $a &=1;
- $h = $a << 1;
- $l = $h + 1;
- $r = 0;
- $r = $this->r16($h)<<16;
- $r |= $this->r16($l);
- return $r;
- }
- function r64(){
- $r = $this->r32(0)<<32;
- $r |= $this->r32(1);
- return $r;
- }
- //Union写数值程序 参数a:地址 参数b:数值 (64位无地址)
- function w8($a,$v){
- $a &=7;
- $a = $this->bas ? $a : $a^7;
- $v &=255;
- $this->value[$a] = $v;
- }
- function w16($a,$v){
- $a &=3;
- $v &=65535;
- $h = $a << 1;
- $l = $h + 1;
- $this->w8($h,$v>>8);
- $this->w8($l,$v);
- }
- function w32($a,$v){
- $a &= 1;
- $v &= 4294967295;
- $h = $a << 1;
- $l = $h + 1;
- $this->w16($h,$v>>16);
- $this->w16($l,$v);
- }
- function w64($v){
- $this->w32(0,$v>>32);
- $this->w32(1,$v);
- }
- function in($data){ //导入数据(固定8字节,成功返回1失败返回0)
- if(strlen($data) != 8) return 0;
- for($i=0;$i<8;$i++){
- $this->value[$i] = ord($data[$i]);
- }
- return 1;
- }
- function out(){ //导出数据(8字节)
- $return = null;
- for($i=0;$i<8;$i++){
- $return .= chr($this->value[$i]);
- }
- return $return;
- }
- function sbas($bas){ //设置大小端 0小端 1大端
- $this->bas = $bas&1;
- }
- function gbas(){ //读取大小端
- return $this->bas;
- }
- }
- $a = new union64;
- $a->in("01234567");
- $a->sbas(1);
- echo dechex($a->r8(0))."<br>";
- echo dechex($a->r8(1))."<br>";
- echo dechex($a->r8(2))."<br>";
- echo dechex($a->r8(3))."<br>";
- echo dechex($a->r8(4))."<br>";
- echo dechex($a->r8(5))."<br>";
- $a->w8(5,0x4D);
- echo dechex($a->r8(6))."<br>";
- echo dechex($a->r8(7))."<br>";
- echo dechex($a->r16(0))."<br>";
- echo dechex($a->r16(1))."<br>";
- echo dechex($a->r16(2))."<br>";
- echo dechex($a->r16(3))."<br>";
- echo dechex($a->r32(0))."<br>";
- echo dechex($a->r32(1))."<br>";
- echo dechex($a->r64())."<br>";
- echo $a->out();
- ?>
复制代码 |
|