in reply to Converting negative number to binary with specific width

YOu're using the wring tool. pack & unpack are designed for this:

print unpack 'b10', pack 's', -1;; 1111111111 print unpack 'b10', pack 's', -21;; 1101011111 print unpack 'b10', pack 's', 1024;; 0000000000

With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority". I knew I was on the right track :)
In the absence of evidence, opinion is indistinguishable from prejudice.
div class=

Replies are listed 'Best First'.
Re^2: Converting negative number to binary with specific width
by AnomalousMonk (Archbishop) on Nov 03, 2015 at 01:34 UTC

    I was thinking something more along the lines of

    c:\@Work\Perl\monks>perl -wMstrict -le "for my $n (-2, -1, 0, 1, 2, 1023, 1024, 1025) { my $bin = reverse unpack 'b10', pack 'v', $n; print qq{'$bin' <= $n}; } " '1111111110' <= -2 '1111111111' <= -1 '0000000000' <= 0 '0000000001' <= 1 '0000000010' <= 2 '1111111111' <= 1023 '0000000000' <= 1024 '0000000001' <= 1025
    to get closer to the  'b' formatting of sprintf (although I'm not sure this is any better than substr-inging it). (Update: Also see perlpacktut.)


    Give a man a fish:  <%-{-{-{-<

      what os the is use of pack 'v' for?

        what os the is use of pack 'v' for?

        The documentation explains it :)

        v An unsigned short (16-bit) in "VAX" (little-endian) order. V An unsigned long (32-bit) in "VAX" (little-endian) order.
Re^2: Converting negative number to binary with specific width
by pjkang7 (Novice) on Nov 05, 2015 at 16:58 UTC

    Yup I will definitely use pack unpack next time. I saw that before but I thought I should not have any problem with sprintf. I did manage to work my way through using substr but I do think pack unpack would work nicer. Thanks

      Make sure you look at AnomalousMonk's version of the code.


      With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority". I knew I was on the right track :)
      In the absence of evidence, opinion is indistinguishable from prejudice.