I need to pad binary strings with zeros. How do I do that?
Suppose I have '1111' but I need it to be '01111'. How would I do that?
I need to pad binary strings with zeros. How do I do that?
Suppose I have '1111' but I need it to be '01111'. How would I do that?
PHP supports automatic type conversion.
so:
<?php
$num = 1111;
$new_num = "0".$num;
?>
Well, there is [man]str_pad/man....
The problem is PHP strips all left 0s from binary strings...I think that's what's happening anyways. So even when I add a 0 like Merve had it or with string pad, it still strips the left zeros. E.g. when I do
$num = 1111;
$new_num = '0'.$num;
echo $num;
I still get an output of 1111 instead of 01111 because that leading 0 gets stripped. The same happens with str_pad when the number is converted to a binary string. Does that happen to anyone else?
I managed to get pack () to work. Here it is in a function:
function padBinStrLeft ($binStr, $leadingZeros) {
$bin = $binStr;
for ($i = 0; $i < $leadingZeros; $i++) $bin = pack ("aa*", 0, $bin);
return $bin;
} // end padBinStrLeft ()
// pad '1111' with 2 zeros
$binStr = padBinStrLeft (1111, 2);
How about this:
<?php
$num = 1111;
$new_num = (string) '0'.$num
echo $num;
?>
Leading 0's on a binary string are considered insignificant digits. Although having leading zeros are handy for output and makes things look pretty. If all you're doing is output, you might try this:
echo sprintf('%08d', $binary); // 8 digits
echo sprintf('%06d', $binary); // 6 digits
echo sprintf('%04d', $binary); // 4 digits
You may find it easier to let [man]sprintf[/man] to handle the padding for you...
Yeah, sprintf didn't work for me either, though I'm not sure why. I just tried it again and it still didn't work. With this code:
$num = 1111;
$new_num = sprintf ('%06d', $num);
echo $num;
I get the output 1111. Any idea why it doesn't give me the extra zeros?
Yeah, left zeros don't change the value of binary strings (01111 == 1111), so PHP drops them (probably for speed?), but I need those zeros in this case because I have to string bit strings together and make sure they're aligned.
$num = 1111;
$new_num = sprintf ('%06d', $num);
echo $num;
This prints out 1111 because you're echoing $num and not $new_num. Try this:
$num = 1111;
$new_num = sprintf ('%06d', $num);
echo $new_num;
Ha ha, I'm retarded. I must have been doing that before too. :rolleyes: