Hi, this is my first question post on PerlMonk. Just fyi, I have searched and tried for some good amount of time (>40min) and decided I could not find out what's wrong with my code. It's a simple one.

Basically, I am trying to convert negative number into specific length (10) binary. And it's simply refusing to do that. Here's the code:

my $neg = -1; my $negBin = sprintf ("010.10b", $neg); print $negBin; #returns a lot of 1s instead of 11_1111_1111. (without +underscores)

Another problem i had was if I am trying to convert 1024 into binary number:

my $num = 1024; my $bin = sprintf ("010.10b", $num); print $bin; #returns 100_0000_0000 instead of 00_0000_0000

Apparently, there's something wrong with my sprintf formating....and I can't figure it out. I have used substr to simply cut the string to my desired length as a way around it but I am still interested to find out what I did wrong... I turn to the wisdom of PerlMonks out there. Thank you.


In reply to Converting negative number to binary with specific width by pjkang7

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.