PHP: bin2hex and working with impossible numbers - php

Haven't slept in awhile, so I'm probably missing something simple. Basically, I am taking a number and converting it to three characters. Max number of possibilities is 256*256*256 (16777216). I convert it with:
public function s_encode($num) {
$num = chr($num / 65536).chr($num / 256).chr($num % 256);
return bin2hex($num);
}
And convert it back with:
public function s_decode($hex) {
$a = pack("H*", $hex);
$b = ord(substr($a, 1, 1));
$c = ord(substr($a, 2, 1));
$d = ord(substr($a, 0, 1));
return (($d * 65536) + ($b * 256)) + $c;
}
What's strange, is this actually works. It does what I want it to, but how could it? In the first code, where I convert it to three characters, the second part of the conversion is:
chr($num / 256)
If the number is greater than 65536, this should cause an error, but it doesn't. If I were to use unpack instead of bin2hex, it will cause an error. bin2hex won't. Why and how is bin2hex so magical?

chr() only looks at the lowest 8 bits of its input:
echo "'".chr(320)."'";
yields...
'#'
as does...
echo "'".chr(64)."'";
http://ideone.com/65Itz

According to the comments in the php docs, chr will take the parameter modulo 256. Even negative integers work. bin2hex doesn't do that operation, and fails on invalid inputs.

Related

PHP bcmod or gmp_mod input type issue

I'm using bcmod and gmp_mod functions in php for handling large numbers.
This works fine:
// large number must be string
$n = "10000000000000000000001";
$y = 1025;
$c = 1025;
// Both works the same (also tested in python)
$y = gmp_mod( (bcpowmod($y, 2, $n) + $c) , $n);
$y = bcmod ( (bcpowmod($y, 2, $n) + $c) , $n);
But the input $n is not static. So I must use type casting like:
$n = (string)10000000000000000000001;
This doesn't work anymore.
for gmp gives this error:
gmp_mod(): Unable to convert variable to GMP - string is not an integer
And about bc, gives me this error:
bcmod(): Division by zero
The problem is, (string) doesn't convert it to string fine. Any idea?
Edit: I found a solution here, but still the input is string:
$bigint = gmp_init("9999999999999999999");
$bigint_string = gmp_strval($bigint);
var_dump($bigint_string);
If You are taking an input for $n it would give you as a string not as int and if you have type casted as int at any point ... taking care the max size of int, the above given no is converted to 1.0E+22 now what happens when you try to type cast (string)1.0E+22 it becomes "1.0E+22" which is obviously just a string and can not be converted to gmp number.
So You need to convert scientific notation to string which will auto include , hence you also need to replace those commas
$n = 10000000000000000000001;
$n = str_replace(",", "", number_format($n));

php convert decimal to hexadecimal

I am extracting a serial from a digital certificate using the built-in OpenSSL library, however, I am having trouble converting this number to hex with precision.
The extracted number is originally in decimal but I need to have it in hex.
The number I am trying to convert is: 114483222461061018757513232564608398004
Here is what I've tried:
dechex() did not work, it returns: 7fffffffffffffff
The closest I could get was this function from the php.net page but it does not convert the whole number on part of it.
function dec2hex($dec) {
$hex = ($dec == 0 ? '0' : '');
while ($dec > 0) {
$hex = dechex($dec - floor($dec / 16) * 16) . $hex;
$dec = floor($dec / 16);
}
return $hex;
}
echo dec2hex('114483222461061018757513232564608398004');
//Result: 5620aaa80d50fc000000000000000000
Here is what I am expecting:
Decimal number: 114483222461061018757513232564608398004
Expected hex: 5620AAA80D50FD70496983E2A39972B4
I can see the correction conversion here:
https://www.mathsisfun.com/binary-decimal-hexadecimal-converter.html
I need a PHP solution.
The problem is that The largest number that can be converted is ... 4294967295 - hence why it's not working for you.
This answer worked for me during a quick test, assuming you have bcmath installed on your server, and you can obtain the number as a string to start with. If you can't, i.e. it begins life as numeric variable, you'll immediately reach PHP's float limit.
// Credit: joost at bingopaleis dot com
// Input: A decimal number as a String.
// Output: The equivalent hexadecimal number as a String.
function dec2hex($number)
{
$hexvalues = array('0','1','2','3','4','5','6','7',
'8','9','A','B','C','D','E','F');
$hexval = '';
while($number != '0')
{
$hexval = $hexvalues[bcmod($number,'16')].$hexval;
$number = bcdiv($number,'16',0);
}
return $hexval;
}
Example:
$number = '114483222461061018757513232564608398004'; // Important: already a string!
var_dump(dec2hex($number)); // string(32) "5620AAA80D50FD70496983E2A39972B4"
Ensure you pass a string into that function, not a numeric variable. In the example you provided in the question, it looks like you can obtain the number as a string initially, so should work if you have bc installed.
Answered by lafor.
How to convert a huge integer to hex in php?
function bcdechex($dec)
{
$hex = '';
do {
$last = bcmod($dec, 16);
$hex = dechex($last).$hex;
$dec = bcdiv(bcsub($dec, $last), 16);
} while($dec>0);
return $hex;
}
Example:
$decimal = '114483222461061018757513232564608398004';
echo "Hex decimal : ".bcdechex($decimal);
This is a big integer, so you need to use a big-integer library like GMP:
echo gmp_strval('114483222461061018757513232564608398004', 16);
// output: 5620aaa80d50fd70496983e2a39972b4
Try this 100% working for any number
<?php
$dec = '114483222461061018757513232564608398004';
// init hex array
$hex = array();
while ($dec)
{
// get modulus // based on docs both params are string
$modulus = bcmod($dec, '16');
// convert to hex and prepend to array
array_unshift($hex, dechex($modulus));
// update decimal number
$dec = bcdiv(bcsub($dec, $modulus), 16);
}
// array elements to string
echo implode('', $hex);
?>

Workaround needed, PHP dechex maximum integer [duplicate]

I have some large HEX values that I want to display as regular numbers, I was using hexdec() to convert to float, and I found a function on PHP.net to convert that to decimal, but it seems to hit a ceiling, e.g.:
$h = 'D5CE3E462533364B';
$f = hexdec($h);
echo $f .' = '. Exp_to_dec($f);
Output: 1.5406319846274E+19 = 15406319846274000000
Result from calc.exe = 15406319846273791563
Is there another method to convert large hex values?
As said on the hexdec manual page:
The function can now convert values
that are to big for the platforms
integer type, it will return the value
as float instead in that case.
If you want to get some kind of big integer (not float), you'll need it stored inside a string. This might be possible using BC Math functions.
For instance, if you look in the comments of the hexdec manual page, you'll find this note
If you adapt that function a bit, to avoid a notice, you'll get:
function bchexdec($hex)
{
$dec = 0;
$len = strlen($hex);
for ($i = 1; $i <= $len; $i++) {
$dec = bcadd($dec, bcmul(strval(hexdec($hex[$i - 1])), bcpow('16', strval($len - $i))));
}
return $dec;
}
(This function has been copied from the note I linked to; and only a bit adapted by me)
And using it on your number:
$h = 'D5CE3E462533364B';
$f = bchexdec($h);
var_dump($f);
The output will be:
string '15406319846273791563' (length=20)
So, not the kind of big float you had ; and seems OK with what you are expecting:
Result from calc.exe =
15406319846273791563
Hope this help ;-)
And, yes, user notes on the PHP documentation are sometimes a real gold mine ;-)
hexdec() switches from int to float when the result is too large to be represented as an int. If you want arbitrarily long values, you're probably going to have to roll your own conversion function to change the hex string to a GMP integer.
function gmp_hexdec($n) {
$gmp = gmp_init(0);
$mult = gmp_init(1);
for ($i=strlen($n)-1;$i>=0;$i--,$mult=gmp_mul($mult, 16)) {
$gmp = gmp_add($gmp, gmp_mul($mult, hexdec($n[$i])));
}
return $gmp;
}
print gmp_strval(gmp_hexdec("D5CE3E462533364B"));
Output: 15406319846273791563
$num = gmp_init( '0xD5CE3E462533364B' ); // way to input a number in gmp
echo gmp_strval($num, 10); // display value in decimal
That's the module to use. Convert it to a function and then use on your numbers.
Note: provide these hex numbers as strings so:
$num = "0x348726837469972346"; // set variable
$gmpnum = gmp_init("$num"); // gmp number format
echo gmp_strval($gmpnum, 10); // convert to decimal and print out
1.5406319846274E+19 is a limited representation of you number. You can have a more complete one by using printf()
printf("%u\n", hexdec($h));
...will output "15406319846273792000". PHP uses floats for such big numbers, so you may lose a bit of precision. If you have to work with arbitrary precision numbers, you may try the bcmath extension. By splitting the hex into two 32-bit words (which should be safe on most systems) you should be able to get more precision. For instance:
$f = bcadd(bcmul(hexdec(substr($h, 0, -8)), 0x100000000), hexdec(substr($h, 8)));
...would set $f to 15406319846273791563.
Convert HEX to DEC is easy.. But, reconstruct back hexadecimal number is very hard.
Try to use base_convert ..
$hexadecimal = base_convert(2826896153644826, 10, 16);
// result: a0b0c0d0e0f1a
Run into this issue while storing 64-bit keys in MySQL database. I was able to get a bit perfect conversion to a 64-bit signed integer (PHP limitation) using a few binary operators: (This code is 16x faster than bchexdec function and resulting variables are using half the memory on average).
function x64toSignedInt($k){
$left = hexdec(substr($k,0,8));
$right = hexdec(substr($k,8,8));
return (int) ($left << 32) | $right;
}
MySQL signed BIGINT datatype is a great match for this as an index or storage in general. HEX(column) is a simple way to convert it back to HEX within the SQL query for use elsewhere.
This solution also uses the BC Math Functions. However, an algorithm is used which does without the bcpow function. This function is a bit shorter and faster than the accepted solution, tested on PHP 7.4.
function hexDecBc(string $hex) : string
{
for ($dec = '0', $i = 0; $i < strlen($hex); $i++) {
$dec = bcadd(bcmul($dec,'16'),(string)hexdec($hex[$i]));
}
return $dec;
}
Make sure to enable gmp extension. ext-gmp
$number = gmp_strval(gmp_init('0x03....')); // outputs: 1234324....
Doesn't intval(var, base) take care of it?
From the PHP Manual.

PHP How do I round down to two decimal places? [duplicate]

This question already has answers here:
Truncate float numbers with PHP
(14 answers)
Closed 11 months ago.
I need to round down a decimal in PHP to two decimal places so that:
49.955
becomes...
49.95
I have tried number_format, but this just rounds the value to 49.96. I cannot use substr because the number may be smaller (such as 7.950). I've been unable to find an answer to this so far.
Any help much appreciated.
This can work: floor($number * 100) / 100
Unfortunately, none of the previous answers (including the accepted one) works for all possible inputs.
1) sprintf('%1.'.$precision.'f', $val)
Fails with a precision of 2 : 14.239 should return 14.23 (but in this case returns 14.24).
2) floatval(substr($val, 0, strpos($val, '.') + $precision + 1))
Fails with a precision of 0 : 14 should return 14 (but in this case returns 1)
3) substr($val, 0, strrpos($val, '.', 0) + (1 + $precision))
Fails with a precision of 0 : -1 should return -1 (but in this case returns '-')
4) floor($val * pow(10, $precision)) / pow(10, $precision)
Although I used this one extensively, I recently discovered a flaw in it ; it fails for some values too. With a precision of 2 : 2.05 should return 2.05 (but in this case returns 2.04 !!)
So far the only way to pass all my tests is unfortunately to use string manipulation. My solution based on rationalboss one, is :
function floorDec($val, $precision = 2) {
if ($precision < 0) { $precision = 0; }
$numPointPosition = intval(strpos($val, '.'));
if ($numPointPosition === 0) { //$val is an integer
return $val;
}
return floatval(substr($val, 0, $numPointPosition + $precision + 1));
}
This function works with positive and negative numbers, as well as any precision needed.
Here is a nice function that does the trick without using string functions:
<?php
function floorp($val, $precision)
{
$mult = pow(10, $precision); // Can be cached in lookup table
return floor($val * $mult) / $mult;
}
print floorp(49.955, 2);
?>
An other option is to subtract a fraction before rounding:
function floorp($val, $precision)
{
$half = 0.5 / pow(10, $precision); // Can be cached in a lookup table
return round($val - $half, $precision);
}
I think there is quite a simple way to achieve this:
$rounded = bcdiv($val, 1, $precision);
Here is a working example. You need BCMath installed but I think it's normally bundled with a PHP installation. :) Here is the documentation.
function roundDown($decimal, $precision)
{
$sign = $decimal > 0 ? 1 : -1;
$base = pow(10, $precision);
return floor(abs($decimal) * $base) / $base * $sign;
}
// Examples
roundDown(49.955, 2); // output: 49.95
roundDown(-3.14159, 4); // output: -3.1415
roundDown(1000.000000019, 8); // output: 1000.00000001
This function works with positive and negative decimals at any precision.
Code example here: http://codepad.org/1jzXjE5L
Multiply your input by 100, floor() it, then divide the result by 100.
You can use bcdiv PHP function.
bcdiv(49.955, 1, 2)
Try the round() function
Like this: round($num, 2, PHP_ROUND_HALF_DOWN);
For anyone in need, I've used a little trick to overcome math functions malfunctioning, like for example floor or intval(9.7*100)=969 weird.
function floor_at_decimals($amount, $precision = 2)
{
$precise = pow(10, $precision);
return floor(($amount * $precise) + 0.1) / $precise;
}
So adding little amount (that will be floored anyways) fixes the issue somehow.
Use formatted output
sprintf("%1.2f",49.955) //49.95
DEMO
You can use:
$num = 49.9555;
echo substr($num, 0, strpos($num, '.') + 3);
function floorToPrecision($val, $precision = 2) {
return floor(round($val * pow(10, $precision), $precision)) / pow(10, $precision);
}
An alternative solution using regex which should work for all positive or negative numbers, whole or with decimals:
if (preg_match('/^-?(\d+\.?\d{1,2})\d*$/', $originalValue, $matches)){
$roundedValue = $matches[1];
} else {
throw new \Exception('Cannot round down properly '.$originalValue.' to two decimal places');
}
Based on #huysentruitw and #Alex answer, I came up with following function that should do the trick.
It pass all tests given in Alex's answer (as why this is not possible) and build upon huysentruitw's answer.
function trim_number($number, $decimalPlaces) {
$delta = (0 <=> $number) * (0.5 / pow(10, $decimalPlaces));
$result = round($number + $delta, $decimalPlaces);
return $result ?: 0; // get rid of negative zero
}
The key is to add or subtract delta based on original number sign, to support trimming also negative numbers.
Last thing is to get rid of negative zeros (-0) as that can be unwanted behaviour.
Link to "test" playground.
EDIT: bcdiv seems to be the way to go.
// round afterwards to cast 0.00 to 0
// set $divider to 1 when no division is required
round(bcdiv($number, $divider, $decimalPlaces), $decimalPlaces);
sprintf("%1.2f",49.955) //49.95
if you need to truncate decimals without rounding - this is not suitable, because it will work correctly until 49.955 at the end, if number is more eg 49.957 it will round to 49.96
It seems for me that Lght`s answer with floor is most universal.
Did you try round($val,2) ?
More information about the round() function

Byte array in PHP

I have a a php string:
e.g. df299cc4cda279e4d7344b42a8006d94488c753f
This is representing a 20 bit HEX output. How would I select the n'th byte? For example if I select the 3rd one it should return 9c.
Thanks.
You can take a look at chunk_split() or str_split() and get a result like:
$string = "df299cc4cda279e4d7344b42a8006d94488c753f";
$bytes = str_split($string, 2);
$yourByte = $bytes[2];
$bytes = str_split($string, 2);
echo $bytes[2];
Or you may want to convert the string to actual binary using hex2bin, then echo the index [2] of the string, possibly converting back to hex for output.
Given $n = byte number (3 in your example) and $data = string with hex output,
return substr($data, ($n - 1) * 2, 2)

Categories