3

i have the variable $a = 5; i want to show it in binary form, with length, equal 8, with writing * at white spaces, just like this, like this * * * * *101


here the script

$number = 5;
printf("%*8b", $number); 

it doesn't work with *, but if "0"-s it works

   printf("%08b", $number);
      //returns 00000101

why it doesn't work with *?

EDIT:

and how can i apply the floating option too? like

`printf("%.4f", $number);` 

    //it returns 5.0000, but i want to return *****101.0000
2
  • about edit - do you want to get binary representation of float? Commented Mar 22, 2010 at 1:48
  • printf("%'*8b.00000", $number); will work for ints. for float and binary output even PHP have no built-in solution as far as I can get. Commented Mar 22, 2010 at 1:53

1 Answer 1

3

http://www.php.net/manual/en/function.sprintf.php

An optional padding specifier that says what character will be used for padding the results to the right string size. This may be a space character or a 0 (zero character). The default is to pad with spaces. An alternate padding character can be specified by prefixing it with a single quote ('). See the examples below.

So, use

printf("%'*8b", $number); 

EDIT:

for float try

printf("%'*.4f", $number); 

and if you want some more complicated cases, just read http://www.php.net/manual/en/function.sprintf.php

Sign up to request clarification or add additional context in comments.

3 Comments

@Syom, and I have no real-world php experience :)
@osgx maybe you worked with perl? there are many functions have the same syntax?
yes, I worked with perl 8 years ago :). printf is taken from C, but padding with alternate char (not space or zero) is, as far as i know, unsupported in most versions of printf. (Only the php has 'a super modification which allow you to do this with only 1 extra char' or 'even this ultra-rare garbage phonetics function is in the core php'). In the perl output can be formatted with "formats", not only with printf. Formats allow to make different padding, but they oriented to work with printable plain text, not html.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.