PHP: Big integer base 10 represented as string to binary string - php

I need to convert a really big integer that is represented as a string to a binary string (aka normal integer, but it is always bigger as normal php integer can hold) to efficiently store it in database and have a unique index on it.
The number comes from GMP (gmp_strval()) and may have different lengths, usually about 200-300 "characters" in it, so it never fits into PHP integer. The idea is to convert it into a binary string representing an integer, kind of big integer. Can I do it with PHP?

Sure you can do this.
Remember how to convert a decimal number to binary by hand.
look if the last digit is even (gives a 0) or odd (gives a 1)
subtract the 1, if you get one.
divide by 2. This have to be done digit by digit as in elementary school :-)
repeat this until your decimalnumber become zero.
I wrote a function for this
function strMod2(array $dec)
{
return ((int)end($dec)) % 2;
}
function strDivBy2(array $dec)
{
$res = [];
$carry = 0;
if($dec[0] == '0')
array_shift($dec);
$len = count($dec);
for($i = 0; $i < $len; $i++)
{
$num = $carry*10 + ((int)$dec[$i]);
$carry = $num % 2;
$num -= $carry;
$res[] = $num / 2;
}
return $res;
}
function dec2bin_str($dec)
{
$dec_arr = str_split($dec);
$bin_arr = [];
while(count($dec_arr) > 1 || $dec_arr[0] != 0)
{
array_unshift($bin_arr, strMod2($dec_arr));
$dec_arr = strDivBy2($dec_arr);
}
return implode($bin_arr);
}
You can use it as
echo dec2bin_str('5'); // '101'
echo dec2bin_str('146456131894613465451'); // '1111111000001111100101101000000000000010100001100010101100101101011'
Maybe this can be done faster by using a library for big integers.

Found Math_BigInteger library that can do it:
$a = new Math_BigInteger($intString);
$base256IntString = $a->toBytes();
https://github.com/pear/Math_BigInteger

Related

Algorithm to find positive and negative integer square roots (without given boundaries)

I've been practicing a lot of algorithms recently for an interview. I was wondering if there was another way to solve this problem. I wrote it in a way where I only increment it positively, because I know from basic math that two negatives multiplied by each other would result to a positive number, so I would just have to make the integer that would satisfy the condition to negative.
Is there a way to write this elegantly where you didn't have the knowledge of multiplying two negative numbers result to a positive?
<?php
# Z = {integers}
# B = {x:x, x is an element of Z, x^2 + 1 = 10}
$numNotFound = true;
$x = 0;
$b = [];
while ($numNotFound) {
if ($x*$x + 1 == 10) {
array_push($b, $x, $x*-1);
$numNotFound = false;
}
$x++;
}
echo json_encode($b); #[3, -3]
Updated
This solution does not use the fact that -1 * -1 = 1. It will output the first number found as the first element in the array. If x=-3 then [-3,3] or if x=3 [3,-3].
$numNotFound = TRUE;
$x = 0;
$b = [];
Do{
if ((pow($x, 2) + 1) === 10) {
array_push($b, $x, 0 - $x);
$numNotFound = FALSE;
}
$x++;
}while($numNotFound);
echo json_encode($b); //[3, -3]

A PHP function to convert decimal ASCII to ASCII char

I'm at a total loss, attempting to convert an decimal string, not oct, just plain decimal, which varies in character count to plain text.
The string would look like:
495051979899100 (123abcd)
I could use chr() all day if I had a way to predict what the string would contain, but I really don't, so what should I do?
Your question is ambiguous in the sense that without any assumption, an input string can result in an exponential number of output strings that all satisfy the constraints.
We make the assumption that with ASCII you mean the readable (not control-parts) of ascii. Thus any valid ascii value is between 32 and 128. As a result, you know that if the first two characters represent a value, strictly less than 32 it will be in the 100+ range.
Your algorithm should do two things concurrently:
Read out the first two characters.
If the value is less than 32 then, the the value is in the 100+ range so read three characters and convert, if not it is in the -100 range, sou convert the two characters.
Or in PHP:
$s = "495051979899100";
$n = strlen($s);
$result = "";
for ($x=0; $x<=$n; $x += 2) {
$temp = intval(substr($s,$x,2));
if($temp < 32) {
$temp = intval(substr($s,$x,3));
if($temp > 128) {
die "Assumption error";
}
$x++;
}
$result .= chr($temp);
}
echo $result;
Yep, wrote almost the same code
$str = '495051979899100';
$ind = 0; $out = '';
while($ind < strlen($str))
{
$two = substr($str, $ind, 2);
if ($two >= 32) {
$out .= chr($two);
$ind += 2;
} else {
$out .= chr(substr($str, $ind, 3));
$ind += 3;
}
}
echo $out;
My fancy way with limitation that char could be from 32 to 128.
$value = '495051979899100';
preg_match_all('/3[2-9]|[4-9][0-9]|1[0-1][0-9]|12[0-8]/', $value, $matches);
var_dump(implode(array_map('chr',$matches[0])));
// string(7) "123abcd"

How to round down to the nearest significant figure in php

Is there any slick way to round down to the nearest significant figure in php?
So:
0->0
9->9
10->10
17->10
77->70
114->100
745->700
1200->1000
?
$numbers = array(1, 9, 14, 53, 112, 725, 1001, 1200);
foreach($numbers as $number) {
printf('%d => %d'
, $number
, $number - $number % pow(10, floor(log10($number)))
);
echo "\n";
}
Unfortunately this fails horribly when $number is 0, but it does produce the expected result for positive integers. And it is a math-only solution.
Here's a pure math solution. This is also a more flexible solution if you ever wanted to round up or down, and not just down. And it works on 0 :)
if($num === 0) return 0;
$digits = (int)(log10($num));
$num = (pow(10, $digits)) * floor($num/(pow(10, $digits)));
You could replace floor with round or ceil. Actually, if you wanted to round to the nearest, you could simplify the third line even more.
$num = round($num, -$digits);
If you do want to have a mathy solution, try this:
function floorToFirst($int) {
if (0 === $int) return 0;
$nearest = pow(10, floor(log($int, 10)));
return floor($int / $nearest) * $nearest;
}
Something like this:
$str = (string)$value;
echo (int)($str[0] . str_repeat('0', strlen($str) - 1));
It's totally non-mathy, but I would just do this utilizing sting length... there's probably a smoother way to handle it but you could acomplish it with
function significant($number){
$digits = count($number);
if($digits >= 2){
$newNumber = substr($number,0,1);
$digits--;
for($i = 0; $i < $digits; $i++){
$newNumber = $newNumber . "0";
}
}
return $newNumber;
}
A math based alternative:
$mod = pow(10, intval(round(log10($value) - 0.5)));
$answer = ((int)($value / $mod)) * $mod;
I know this is an old thread but I read it when looking for inspiration on how to solve this problem. Here's what I came up with:
class Math
{
public static function round($number, $numberOfSigFigs = 1)
{
// If the number is 0 return 0
if ($number == 0) {
return 0;
}
// Deal with negative numbers
if ($number < 0) {
$number = -$number;
return -Math::sigFigRound($number, $numberOfSigFigs);
}
return Math::sigFigRound($number, $numberOfSigFigs);
}
private static function sigFigRound($number, $numberOfSigFigs)
{
// Log the number passed
$log = log10($number);
// Round $log down to determine the integer part of the log
$logIntegerPart = floor($log);
// Subtract the integer part from the log itself to determine the fractional part of the log
$logFractionalPart = $log - $logIntegerPart;
// Calculate the value of 10 raised to the power of $logFractionalPart
$value = pow(10, $logFractionalPart);
// Round $value to specified number of significant figures
$value = round($value, $numberOfSigFigs - 1);
// Return the correct value
return $value * pow(10, $logIntegerPart);
}
}
While the functions here worked, I needed significant digits for very small numbers (comparing low-value cryptocurrency to bitcoin).
The answer at Format number to N significant digits in PHP worked, somewhat, though very small numbers are displayed by PHP in scientific notation, which makes them hard for some people to read.
I tried using number_format, though that needs a specific number of digits after the decimal, which broke the 'significant' part of the number (if a set number is entered) and sometimes returned 0 (for numbers smaller than the set number).
The solution was to modify the function to identify really small numbers and then use number_format on them - taking the number of scientific notation digits as the number of digits for number_format:
function roundRate($rate, $digits)
{
$mod = pow(10, intval(round(log10($rate))));
$mod = $mod / pow(10, $digits);
$answer = ((int)($rate / $mod)) * $mod;
$small = strstr($answer,"-");
if($small)
{
$answer = number_format($answer,str_replace("-","",$small));
}
return $answer;
}
This function retains the significant digits as well as presents the numbers in easy-to-read format for everyone. (I know, it is not the best for scientific people nor even the most consistently length 'pretty' looking numbers, but it is overall the best solution for what we needed.)

How to generate random 64-bit value as decimal string in PHP

Oauth requires a random 64-bit, unsigned number encoded as an ASCII string in decimal format. Can you guys help me achieve this with php?
Thanks
This was a really interesting problem (how to create the decimal representation of an arbitrary-length random number in PHP, using no optional extensions). Here's the solution:
Step 1: arbitrary-length random number
// Counts how many bits are needed to represent $value
function count_bits($value) {
for($count = 0; $value != 0; $value >>= 1) {
++$count;
}
return $count;
}
// Returns a base16 random string of at least $bits bits
// Actual bits returned will be a multiple of 4 (1 hex digit)
function random_bits($bits) {
$result = '';
$accumulated_bits = 0;
$total_bits = count_bits(mt_getrandmax());
$usable_bits = intval($total_bits / 8) * 8;
while ($accumulated_bits < $bits) {
$bits_to_add = min($total_bits - $usable_bits, $bits - $accumulated_bits);
if ($bits_to_add % 4 != 0) {
// add bits in whole increments of 4
$bits_to_add += 4 - $bits_to_add % 4;
}
// isolate leftmost $bits_to_add from mt_rand() result
$more_bits = mt_rand() & ((1 << $bits_to_add) - 1);
// format as hex (this will be safe)
$format_string = '%0'.($bits_to_add / 4).'x';
$result .= sprintf($format_string, $more_bits);
$accumulated_bits += $bits_to_add;
}
return $result;
}
At this point, calling random_bits(2048) will give you 2048 random bits as a hex-encoded string, no problem.
Step 2: arbitrary-precision base conversion
Math is hard, so here's the code:
function base_convert_arbitrary($number, $fromBase, $toBase) {
$digits = '0123456789abcdefghijklmnopqrstuvwxyz';
$length = strlen($number);
$result = '';
$nibbles = array();
for ($i = 0; $i < $length; ++$i) {
$nibbles[$i] = strpos($digits, $number[$i]);
}
do {
$value = 0;
$newlen = 0;
for ($i = 0; $i < $length; ++$i) {
$value = $value * $fromBase + $nibbles[$i];
if ($value >= $toBase) {
$nibbles[$newlen++] = (int)($value / $toBase);
$value %= $toBase;
}
else if ($newlen > 0) {
$nibbles[$newlen++] = 0;
}
}
$length = $newlen;
$result = $digits[$value].$result;
}
while ($newlen != 0);
return $result;
}
This function will work as advertised, for example try base_convert_arbitrary('ffffffffffffffff', 16, 10) == '18446744073709551615' and base_convert_arbitrary('10000000000000000', 16, 10) == '18446744073709551616'.
Putting it together
echo base_convert_arbitrary(random_bits(64), 16, 10);
You could use two 32-bit numbers, four 16-bit numbers, etc.
PHP has rand() and and mt_rand() but how many random bits they supply isn't specified by the standard (though they can be queried with the help of getrandmax() and mt_getrandmax(), respectively.)
So your safest simplest bet would be generating 64 random bits and setting them one by one.
As for working with 64-bit integers, I'd recommend using the GMP library as it has a good range of functions to help you out.
You could create a number, call 64 gmp_setbit()s on it with successive positions then convert it to a string using gmp_strval().
Are you building an OAuth adapter yourself? If so, you might want to reconsider. There are plenty of good OAuth libraries out there, including one from PECL, one in PEAR, another from the Zend Framework, and this other one hosted on Google Code. I've worked with the first three, and they're all pretty decent.
If you really want to do this yourself, you may face an issue. PHP can't think in 64-bit numbers unless it's compiled on a 64-bit platform or you have an advanced mathematics extension installed. This is going to make presenting a 64-bit number as a decimal very difficult. It looks like many of the libraries I linked above completely ignore the format requirement and simply work with a raw MD5 hash. Here's the code from ZF's adapter:
/**
* Generate nonce
*
* #return string
*/
public function generateNonce()
{
return md5(uniqid(rand(), true));
}
They look like they're getting away with this without interoperability issues.

Calculating 0's and 1's in PHP

I want to calculate Frequency (Monobits) test in PHP:
Description: The focus of the test is
the proportion of zeroes and ones for
the entire sequence. The purpose of
this test is to determine whether that
number of ones and zeros in a sequence
are approximately the same as would be
expected for a truly random sequence.
The test assesses the closeness of the
fraction of ones to ½, that is, the
number of ones and zeroes in a
sequence should be about the same.
I am wondering that do I really need to calculate the 0's and 1's (the bits) or is the following adequate:
$value = 0;
// Loop through all the bytes and sum them up.
for ($a = 0, $length = strlen((binary) $data); $a < $length; $a++)
$value += ord($data[$a]);
// The average should be 127.5.
return (float) $value/$length;
If the above is not the same, then how do I exactly calculate the 0's and 1's?
No, you really need to check all zeroes and ones. For example, take the following binary input:
01111111 01111101 01111110 01111010
. It is clearly (literally) one-sided(8 zeroes, 24 ones, correct result 24/32 = 3/4 = 0.75) and therefore not random. However, your test would compute 125.0 /255 which is close to ½.
Instead, count like this:
function one_proportion($binary) {
$oneCount = 0;
$len = strlen($binary);
for ($i = 0;$i < $len;$i++) {
$intv = ord($binary{$i});
for ($bitp = 0;$bitp < 7;$bitp++) {
$oneCount += ($intv>>$bitp) & 0x1;
}
}
return $oneCount / (8 * $len);
}

Categories