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;
}

usage:

// 96-digit binary string
$str = '000000000011110000000000000000001111111111111111111111111111111111111111000000000000000000001111';

$strChars = binStr2charStr($str);
// "\x00<\x00\x00\xff\xff\xff\xff\xff\x00\x00\x0f"

//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:

base_convert(ord($temp), 10, 2)

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));
}

Output

string '25,648,639.00' (length=13) <---- Length Grater than 17,747,595
float 1.0633520126343 <---------------- Total Conversion Time

Links

  • Original Dictionary File (349,900 words) 3,131KB
  • Binary Version 25,048 KB

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 binaryDecodein the dump.

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

writeDump([
binaryData,
hexEncoded,
base64Encoded,
binaryDecode(hexEncoded, "hex"),
binaryDecode(base64Encoded, "base64")
]);
</cfscript>

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 <- sample(1:100, 30)
df <- data.frame(x = data, y = 2 * data + 20)
model <- lm(y ~ x, df)

# 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 <- eval(parse(text = mstr))

# Parse the formulas
model1$terms <- terms.formula(model1$terms)


# ----- Test it -----
# New data
df1 <- data.frame(x = 101:110)

pred <- as.integer(predict(model, df1))
pred1 <- as.integer(predict(model1, df1))

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)


Related Topics



Leave a reply



Submit