mAineAc has asked for the wisdom of the Perl Monks concerning the following question:

I am using this function:
sub dec2bin {
    my $binary = unpack("B32", pack("N", shift));
    $binary =~ s/^0+(?=\d)//;   # otherwise you'll get leading zeros
    return $binary;
}
to convert to binary numbers. It works good but I want to limit the numbers to 8 places to represent an 8 bit binary number. I have limited the number size to 127 so that works for positive numbers but negative numbers tend to put many 1's in front of the number. What would be a good way of going about this?

Replies are listed 'Best First'.
Re: binary numbers (N->C, 32->8)
by tye (Sage) on Jan 30, 2004 at 04:49 UTC
    sub dec2bin8 { my $binary = unpack "B8", pack "C", shift(@_); $binary =~ s/^0+(?=\d)//; # otherwise you'll get leading zeros return $binary; }

    - tye        

Re: binary numbers
by duff (Parson) on Jan 30, 2004 at 15:50 UTC

    You've been adequately answered from what I can see, but I did want to comment on the language used in your post. You say things like

    convert to binary numbers
    This often indicates a misunderstanding of the universe (granted it may not in your case, but for everyone else's benefit...). The number is the same. It's not a binary number, it's a binary representation of a number. The number is exactly the same. It could be represented in hex, binary, octal, sexagesimal, whatever, it's still the same number. The main reason I mention this is that I see it all the time where people confuse the number with the representation of that number.

    This has been a public service announcement. We now return you to your regularly scheduled monastery

      With that reasoning, there are no binary numbers. There are no octal numbers. There are no decimal numbers. Yet, anyone understands what you mean if you talk about 'binary numbers' or 'octal numbers'.

      Admit it, it's much easier to talk about "binary numbers" than "binary representations of numbers". Even in the PODs we speak of binary numbers when we mean the representation.

      Binary number > 0b11111111111111111111111111111111 non- portable (W portable) The binary number you specified is larger than 2**32-1 (4294967295) and therefore non-portable between systems. See perlport for more on portability concerns. Illegal binary digit %s ignored (W digit) You may have tried to use a digit other than 0 or 1 in a binary number. Interpretation of the binary number stopped before the offending digit. Integer overflow in %s number (W overflow) The hexadecimal, octal or binary number you have specified either as a literal or as an argu- ment to hex() or oct() is too big for your architec- ture, and has been converted to a floating point num- ber. On a 32-bit architecture the largest hexadeci- mal, octal or binary number representable without overflow is 0xFFFFFFFF, 037777777777, or 0b11111111111111111111111111111111 respectively. Note that Perl transparently promotes all numbers to a floating point representation internally--subject to loss of precision errors in subsequent operations. -- perldiag SYNOPSIS $n = 1234; # decimal integer $n = 0b1110011; # binary integer $n = 01234; # octal integer $n = 0x1234; # hexadecimal integer $n = 12.34e-56; # exponential notation $n = "-12.34e56"; # number specified as a string $n = "1234"; # number specified as a string -- perlnumber grok_bin converts a string representing a binary number to numeric form. The hex number may optionally be prefixed with "0b" or "b" unless "PERL_SCAN_DISALLOW_PREFIX" is set in *flags on entry. If "PERL_SCAN_ALLOW_UNDER- SCORES" is set in *flags then the binary number may use '_' characters to separate digits. -- perlapi
      Each time it mentions 'binary number', it means 'the representation of a number in binary'.

      Abigail

        Wow and I thought someone punched my button! ;-)

        Sure, I'll admit it's easier to talk about "binary numbers" or "hexadecimal numbers". All I am saying is a word of caution to those that might be confused: don't get fooled into thinking that hex 20 and decimal 32 and octal 040 and binary 100000 are all different numbers. They are all the same number just represented differently.

      Perhaps unfortunately, the term "binary" has acquired several related but different meanings such that terms like "binary number" and phrases like "conver to binary" can be quite ambiguous.

      Since "binary" is often used to refer to the internal or "raw" format of data, I will usually use "base-2" when talking about representing a numeric value in a string using only the characters '1' and '0'.

      There is also the term "numeral" which is probably a more precise term to use instead of "number" when talking about repesentations in different bases. A numeral is a representation of a number. IMHO, "hexadecimal number" is just sloppy vernacular for "hexadecimal numeral", and such is just fine in most cases.

      When making a distinction between a number's value and its representation, the term "numeral" might be handy except that I expect many don't know the term well and probably think it is just a synonym for "number".

      So one could talk about getting "the base-2 numeral for a numeric value" and be very precise and unambiguous, and probably not be as well understood. I'm not trying to draw some meaningful conclusion from this observation; I just find it interesting.

      - tye        

Re: binary numbers
by Anonymous Monk on Jan 30, 2004 at 03:13 UTC
    my $num = shift; if ( $num < 0 ) { $num ^= (~0) ^ 255 };

      Surely a simpler way would be

      # Trim number to 8 bits my $num = 0xff & shift;
Re: binary numbers
by mAineAc (Novice) on Jan 30, 2004 at 15:57 UTC
    Than you everyone. I appreciate the help.