Php char to binary

hex2bin

This function does NOT convert a hexadecimal number to a binary number. This can be done using the base_convert() function.

Parameters

Hexadecimal representation of data.

Return Values

Returns the binary representation of the given data or false on failure.

Errors/Exceptions

If the hexadecimal input string is of odd length or invalid hexadecimal string an E_WARNING level error is thrown.

Examples

Example #1 hex2bin() example

The above example will output something similar to:

string(16) "example hex data"

See Also

  • bin2hex() — Convert binary data into hexadecimal representation
  • unpack() — Unpack data from binary string

User Contributed Notes 13 notes

The function hex2bin does not exist in PHP5.
You can use ‘pack’ instead :

$binary_string = pack(«H*» , $hex_string);

if you want to convert a hex encoded string to a binary string without any notices/errors regardless of the input, use this function:

function hex2binary ( $str )
return ctype_xdigit ( strlen ( $str ) % 2 ? «» : $str ) ? hex2bin ( $str ) : false ;
>

hex2binary ( «» ); // false
hex2binary ( «a» ); // false
hex2binary ( «ab» ); // binary-string

?>

if the return type is string, you have your binary-string. otherwise (bool) false.

I modified the function by Johnson a bit so it can be used as a drop-in-replacement. You don’t need to worry about upgrading php because when it is upgraded, it will use the build in function.

if ( ! function_exists ( ‘hex2bin’ ) ) function hex2bin ( $str ) $sbin = «» ;
$len = strlen ( $str );
for ( $i = 0 ; $i < $len ; $i += 2 ) $sbin .= pack ( "H*" , substr ( $str , $i , 2 ) );
>

The function pack(«H*» , $hex_string); will not work as expected if $hex_string contains an odd number of hexadecimal digits.

#error:
hex2bin(): Hexadecimal input string must have an even length

For those who are facing the error above trying to convert hex to bin. you can pad your hex string with initial 0 before hex2bin.

function hexPad(string $hex_string)
$st_l = strlen($hex_string);
return str_pad($hex_string, $st_l + ($st_l % 2), ‘0’, STR_PAD_LEFT);
>

for usage hex2bin(hexPad(‘1bc’));

If you want to convert hex to GUID format (In my case, it was to convert GUID from MSSQL database) :

function hex2Guid ( $hex )
$hex = [
substr ( $hex , 0 , 8 ),
substr ( $hex , 8 , 4 ),
substr ( $hex , 12 , 4 ),
substr ( $hex , 16 , 4 ),
substr ( $hex , 20 ),
];

$order [ 0 ] = [ 6 , 7 , 4 , 5 , 2 , 3 , 0 , 1 ];
$order [ 1 ] = [ 2 , 3 , 0 , 1 ];
$order [ 2 ] = [ 2 , 3 , 0 , 1 ];
$order [ 3 ] = [ 0 , 1 , 2 , 3 ];
$order [ 4 ] = [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 ];

return strtoupper ( $result );
>

Example :
echo hex2Guid ( «64d3938b7008cd4bad5ffe56755d163f» );

Case of an incomplete hex string following function may help:
function make2validhex ( $data ) $data = (string) $data ;
$len = strlen ( $data );
if( $len % 2 ) return substr ( $data , 0 , $len — 1 );
>
return $data ;
>
?>
test:
$string = «not complete» ;
echo $string ;
echo PHP_EOL ;
$hex = bin2hex ( $string ); //»6e6f7420636f6d706c657465″
echo $hex ;
echo PHP_EOL ;
$deff = substr ( $hex , 0 , strlen ( $hex ) — 1 ); //»6e6f7420636f6d706c65746″
echo $deff ;
echo PHP_EOL ;
echo hex2bin ( make2validhex ( $deff )); //»not complet»
echo PHP_EOL ;
?>

For those who have php version prior to 5.4, i have a solution to convert hex to binary. It works for me in an encryption and decryption application.

function hextobin ( $hexstr )
<
$n = strlen ( $hexstr );
$sbin = «» ;
$i = 0 ;
while( $i < $n )
<
$a = substr ( $hexstr , $i , 2 );
$c = pack ( «H*» , $a );
if ( $i == 0 ) < $sbin = $c ;>
else < $sbin .= $c ;>
$i += 2 ;
>
return $sbin ;
>
?>

A drop-in hex2bin emulator which behaves just like the the one in v5.5.1.

if (! function_exists ( ‘hex2bin’ )) function hex2bin ( $data ) static $old ;
if ( $old === null ) $old = version_compare ( PHP_VERSION , ‘5.2’ , ‘ >
$isobj = false ;
if ( is_scalar ( $data ) || (( $isobj = is_object ( $data )) && method_exists ( $data , ‘__toString’ ))) if ( $isobj && $old ) ob_start ();
echo $data ;
$data = ob_get_clean ();
>
else $data = (string) $data ;
>
>
else trigger_error ( __FUNCTION__ . ‘() expects parameter 1 to be string, ‘ . gettype ( $data ) . ‘ given’ , E_USER_WARNING );
return; //null in this case
>
$len = strlen ( $data );
if ( $len % 2 ) trigger_error ( __FUNCTION__ . ‘(): Hexadecimal input string must have an even length’ , E_USER_WARNING );
return false ;
>
if ( strspn ( $data , ‘0123456789abcdefABCDEF’ ) != $len ) trigger_error ( __FUNCTION__ . ‘(): Input string must be hexadecimal string’ , E_USER_WARNING );
return false ;
>
return pack ( ‘H*’ , $data );
>
>
?>

$test = bin2hex(‘sample . ‘);
echo _hex2bin($test);

// another hex2bin replacement
function _hex2bin($result) $out = »;
for($c=0;$c > //end for
return (string) $out;
>

A way to convert hex strings in the form «0x123ABC» to integer is to use the function base_convert(«0x123ABC», 16, 10)

function Hex2Bin($data) $BinData = «»;
for ($i=0;$i $BinData .= chr( HexDec( substr($data,$i,2) ) );
return $BinData;

Источник

Convert String to Binary Then Back Again Using PHP

How to convert a large binary string to a binary value and back

These functions convert bit strings to binary character strings and back.

function binStr2charStr(string $binStr) : string
$rest8 = strlen($binStr)%8;
if($rest8) $binStr = str_repeat('0', 8 - $rest8).$binStr;
>
$strChar = "";
foreach(str_split($binStr,8) as $strBit8) $strChar .= chr(bindec($strBit8));
>
return $strChar;
>


function charStr2binStr(string $charStr) : string
$strBin = "";
foreach(str_split($charStr,1) as $char) $strBin .= str_pad(decbin(ord($char)),8,'0', STR_PAD_LEFT);
>
return $strBin;
>
// 96-digit binary string
$str = '000000000011110000000000000000001111111111111111111111111111111111111111000000000000000000001111';

$strChars = binStr2charStr($str);
// "\x00
//back
$strBin = charStr2binStr($strChars);

Converting string to binary and back to string is not the same with PHP

Using pack() with h* (or h ) is what you want here. You are reading it in as a hex value (after converting from binary), so you want pack to see it as a hex value.

$temp = pack('h', base_convert($binary, 2, 16));

The problem was when you convert it back. ord returns you a base 10 number. I was incorrectly converting it as a hex (base 16) value:

Though, after looking at the code again, I think you don’t even need pack() here. You are using ord() , so we can use its opposite, chr() :

$temp = chr(base_convert($binary, 2, 10));

chr() wants a (base 10) int though, not a hex value, so let’s use that.

What seems to be working is the following:

$temp = chr(base_convert($binary, 2, 10));
echo str_pad(base_convert(ord($temp), 10, 2), 8, '0', STR_PAD_LEFT);

PHP Efficient way to Convert String of Binary into Binary

You don’t need to loop you can use gmp with pack

$file = "binary.txt";
$string = file_get_contents($file);
$start = microtime(true);

// Convert the string
$string = simpleConvert($string);
//echo $string ;

var_dump(number_format(filesize($file),2),microtime(true)- $start);

function simpleConvert($string) return pack('H*',gmp_strval(gmp_init($string, 2), 16));
>
string '25,648,639.00' (length=13) float 1.0633520126343

Note Solution requires GMP Functions

Converting binary value to string and back to binary?

Your working with binary data, and not with string encodings. You will need to use binaryEncoded and binaryDecode to send your data as a string and convert it back to binary.

The following example converts some binary data into 2 string representations and converts them back into the same byte array with binaryDecode in the dump.

 
binaryData = toBinary("SomeBinaryData++");
hexEncoded = binaryEncode(binaryData, "hex");
base64Encoded = binaryEncode(binaryData, "base64");

writeDump([
binaryData,
hexEncoded,
base64Encoded,
binaryDecode(hexEncoded, "hex"),
binaryDecode(base64Encoded, "base64")
]);

Run the example on TryCF.com

convert string back into object in r

I’m assuming you used base::dput() according to the following example (based on this answer):

# Generate some model over some data
data df model
# Assuming this is what you did you have the model structure inside model.R
dput(model, control = c("quoteExpressions", "showAttributes"), file = "model.R")


# ----- This is where you are, I presume -----
# So you can copy the content of model.R here (attention to the single quotes)
mstr
# Execute the content of mstr as a piece of code (loading the model)
model1
# Parse the formulas
model1$terms

# ----- Test it -----
# New data
df1
pred pred1
identical(pred, pred1)
# [1] TRUE


model
#
# Call:
# lm(formula = y ~ x, data = df)
#
# Coefficients:
# (Intercept) x
# 20 2
#

model1
#
# Call:
# lm(formula = y ~ x, data = df)
#
# Coefficients:
# (Intercept) x
# 20 2

# Check summary too (you'll see some minor differences)
# summary(model)
# summary(model1)

Источник

ASCII to Binary in PHP

Recently I inherited a project where all file attachments were stored in a database table in the format of `0xFFD8FFE000104A4649` I need PHP to be able to read and serve this data.

My first thought was to try using base64_decode in case this was in a base64 encoding format. It wasn’t.

Turns out it’s in Ascii format.

Solution 1

The below block converts the data into a format PHP can read by issuing a shell command xxd with -r and -p options passing the command to a proc_open command to run and then using fwrite to return the data to `$source`

$file = '0xFFD8FFE000104A4649. '; //var containing the source data $desc = array( 0 => array('pipe', 'r'), // 0 is STDIN for process 1 => array('pipe', 'w') // 1 is STDOUT for process ); $cmd = "xxd -r -p -"; $p = proc_open($cmd, $desc, $pipes); fwrite($pipes[0], $file); fclose($pipes[0]); $source = stream_get_contents($pipes[1]); fclose($pipes[1]); proc_close($p);

Whilst this works it does rely on being able to run shell commands on your server.

Solution 2

Another way is to use hex2bin function and remove the 0x characters from the data, this essentially does the same thing but the hex2bin does the heavy lifting.

$source = hex2bin(ltrim(rtrim($file), '0x'));

If you’re working with an image you can then output the image using base64 encoding:

Or use headers to render directly:

header('Content-type: image/jpg'); header('Content-Length: ' . strlen($source)); echo base64_encode($source);

Источник

Читайте также:  Python from import views
Оцените статью