Skip to content

Instantly share code, notes, and snippets.

@moriyoshi
Created August 4, 2009 03:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moriyoshi/161004 to your computer and use it in GitHub Desktop.
Save moriyoshi/161004 to your computer and use it in GitHub Desktop.
<?php
function dqn_to_bytes($val) {
$c0 = 0;
$c1 = 0;
for ($i = 0; $i < 32; $i++) {
$q = floor($val / 2);
$b = $val - $q * 2;
$c0 |= $b << $i;
$val = $q;
}
for ($i = 0; $i < 20; $i++) {
$q = floor($val / 2);
$b = $val - $q * 2;
$c1 |= $b << $i;
$val = $q;
}
return pack('VV', $c0, $c1);
}
function dqn_to_hex($val) {
$retval = '';
do {
$q = floor($val / 16);
$r = $val - $q * 16;
$retval .= $r >= 10 ? chr(0x61 + $r - 10): chr(0x30 + $r);
$val = $q;
} while ($val > 0);
return strrev($retval);
}
function dqn_from_bytes($str) {
list(, $c0, $c1) = unpack('V2', $str);
$retval = (float)$c1;
for ($i = 32; --$i >= 0; ) {
$retval = $retval * 2 + (int)($c0 < 0);
$c0 <<= 1;
}
return $retval;
}
function dqn_from_decstr($str) {
$e = strlen($str);
$retval = 0.0;
for ($i = 0; $i < $e; $i++) {
$retval = $retval * 10 + ord($str{$i}) - 0x30;
}
return $retval;
}
function dqn_or($lhs, $rhs) {
return dqn_from_bytes(dqn_to_bytes($lhs) | dqn_to_bytes($rhs));
}
function dqn_and($lhs, $rhs) {
return dqn_from_bytes(dqn_to_bytes($lhs) & dqn_to_bytes($rhs));
}
function dqn_xor($lhs, $rhs) {
return dqn_from_bytes(dqn_to_bytes($lhs) ^ dqn_to_bytes($rhs));
}
class Long52 {
private $val;
function __construct($val) {
$this->val = is_string($val) ? dqn_from_decstr($val): $val;
}
function or_($rhs) {
return new Long52(dqn_or($this->val, $rhs instanceof Long52 ? $rhs->val: $rhs));
}
function and_($rhs) {
return new Long52(dqn_and($this->val, $rhs instanceof Long52 ? $rhs->val: $rhs));
}
function xor_($rhs) {
return new Long52(dqn_xor($this->val, $rhs instanceof Long52 ? $rhs->val: $rhs));
}
function toFloat() {
return $this->val;
}
function toHexString() {
return dqn_to_hex($this->val);
}
function toBytes() {
return dqn_to_bytes($this->val);
}
function __toString() {
return sprintf("%.0f", $this->val);
}
}
printf("%.0f\n", dqn_from_bytes("abcdef\x00\x00"));
var_dump(dqn_to_hex(dqn_from_bytes("abcdef\x00\x00")));
var_dump(dqn_to_bytes(dqn_from_bytes("abcdef\x00\x00")));
printf("%.0f\n", dqn_or(4294967296.0, 4294967296.0));
printf("%.0f\n", dqn_or(4294967296.0, 4294967296.0 * 2));
printf("%.0f\n", dqn_and(4294967296.0, 4294967296.0));
printf("%.0f\n", dqn_and(4294967296.0, 4294967296.0 * 2));
printf("%.0f\n", dqn_xor(4294967296.0, 4294967296.0));
printf("%.0f\n", dqn_xor(4294967296.0, 4294967296.0 * 2));
$val = new Long52("4294967296");
var_dump($val->or_(16777216)->or_(2)->or_(4)->toHexString());
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment