ch02_05.htm
来自「By Tom Christiansen and Nathan Torkingto」· HTM 代码 · 共 423 行
HTM
423 行
<HTML><HEAD><TITLE>Recipe 2.4. Converting Between Binary and Decimal (Perl Cookbook)</TITLE><METANAME="DC.title"CONTENT="Perl Cookbook"><METANAME="DC.creator"CONTENT="Tom Christiansen & Nathan Torkington"><METANAME="DC.publisher"CONTENT="O'Reilly & Associates, Inc."><METANAME="DC.date"CONTENT="1999-07-02T01:30:05Z"><METANAME="DC.type"CONTENT="Text.Monograph"><METANAME="DC.format"CONTENT="text/html"SCHEME="MIME"><METANAME="DC.source"CONTENT="1-56592-243-3"SCHEME="ISBN"><METANAME="DC.language"CONTENT="en-US"><METANAME="generator"CONTENT="Jade 1.1/O'Reilly DocBook 3.0 to HTML 4.0"><LINKREV="made"HREF="mailto:online-books@oreilly.com"TITLE="Online Books Comments"><LINKREL="up"HREF="ch02_01.htm"TITLE="2. Numbers"><LINKREL="prev"HREF="ch02_04.htm"TITLE="2.3. Rounding Floating-Point Numbers"><LINKREL="next"HREF="ch02_06.htm"TITLE="2.5. Operating on a Series of Integers"></HEAD><BODYBGCOLOR="#FFFFFF"><img alt="Book Home" border="0" src="gifs/smbanner.gif" usemap="#banner-map" /><map name="banner-map"><area shape="rect" coords="1,-2,616,66" href="index.htm" alt="Perl Cookbook"><area shape="rect" coords="629,-11,726,25" href="jobjects/fsearch.htm" alt="Search this book" /></map><div class="navbar"><p><TABLEWIDTH="684"BORDER="0"CELLSPACING="0"CELLPADDING="0"><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch02_04.htm"TITLE="2.3. Rounding Floating-Point Numbers"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 2.3. Rounding Floating-Point Numbers"BORDER="0"></A></TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><B><FONTFACE="ARIEL,HELVETICA,HELV,SANSERIF"SIZE="-1"><ACLASS="chapter"REL="up"HREF="ch02_01.htm"TITLE="2. Numbers"></A></FONT></B></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch02_06.htm"TITLE="2.5. Operating on a Series of Integers"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 2.5. Operating on a Series of Integers"BORDER="0"></A></TD></TR></TABLE></DIV><DIVCLASS="sect1"><H2CLASS="sect1"><ACLASS="title"NAME="ch02-10900">2.4. Converting Between Binary and Decimal</A></H2><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch02-pgfId-315">Problem <ACLASS="indexterm"NAME="ch02-idx-1000008009-0"></A><ACLASS="indexterm"NAME="ch02-idx-1000008009-1"></A><ACLASS="indexterm"NAME="ch02-idx-1000008009-2"></A><ACLASS="indexterm"NAME="ch02-idx-1000008009-3"></A></A></H3><PCLASS="para">You have an integer whose binary representation you'd like to print out, or a binary representation that you'd like to convert into an integer. You might want to do this if you were displaying non-textual data, such as what you get from interacting with certain system programs and functions.</P></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch02-pgfId-321">Solution</A></H3><PCLASS="para">To convert a Perl integer to a text string of ones and zeros, first pack the integer into a number in network byte order[<ACLASS="footnote"HREF="#ch02-pgfId-1000000756">1</A>] (the "<CODECLASS="literal">N</CODE>" format), then unpack it again bit by bit (the "<CODECLASS="literal">B32</CODE>" format).</P><BLOCKQUOTECLASS="footnote"><DIVCLASS="footnote"><PCLASS="para"><ACLASS="footnote"NAME="ch02-pgfId-1000000756">[1]</A> Also known as <ICLASS="firstterm">big-endian</I>, or <ICLASS="firstterm">MSB</I> (Most-Significant Bit first) order.</P></DIV></BLOCKQUOTE><PRECLASS="programlisting">sub dec2bin { my $str = unpack("B32", pack("N", shift)); $str =~ s/^0+(?=\d)//; # otherwise you'll get leading zeros return $str;}</PRE><PCLASS="para">To convert a text string of ones and zeros to a Perl integer, first massage the string by padding it with the right number of zeros, then just reverse the previous procedure.</P><PRECLASS="programlisting">sub bin2dec { return unpack("N", pack("B32", substr("0" x 32 . shift, -32)));}</PRE></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch02-pgfId-345">Discussion</A></H3><PCLASS="para">We're talking about converting between strings like "<CODECLASS="literal">00100011</CODE>" and numbers like 35. The string is the binary representation of the number. We can't solve either problem with <CODECLASS="literal">sprintf</CODE> (which doesn't have a "print this in binary" format), so we have to resort to Perl's <CODECLASS="literal">pack</CODE> and <CODECLASS="literal">unpack</CODE> functions for manipulating strings of data.</P><PCLASS="para">The <CODECLASS="literal">pack</CODE><ACLASS="indexterm"NAME="ch02-idx-1000008015-0"></A><ACLASS="indexterm"NAME="ch02-idx-1000008015-1"></A> and <CODECLASS="literal">unpack</CODE> functions act on strings. You can treat the string as a series of bits, bytes, integers, long integers, floating-point numbers in IEEE representation, checksums - among other strange things. The <CODECLASS="literal">pack</CODE> and <CODECLASS="literal">unpack</CODE> functions both take formats, like <CODECLASS="literal">sprintf</CODE>, specifying what they should do with their arguments.</P><PCLASS="para">We use <CODECLASS="literal">pack</CODE> and <CODECLASS="literal">unpack</CODE> in two ways: "treat this string as a series of bits" and "treat this string as containing a binary representation of an integer." When we treat the string as a series of bits, we have to understand how <CODECLASS="literal">pack</CODE> will behave. Such a string is treated as a series of bytes, a byte being eight bits. The bytes are always counted from left to right (the first eight bits are the first byte, the next eight bits are the second, and so on), but the bits within each byte can be counted left-to-right as well as right-to-left.</P><PCLASS="para">We use <CODECLASS="literal">pack</CODE> with a template of "<CODECLASS="literal">B</CODE>" to work with bits within each byte from left to right. This is the order that the "<CODECLASS="literal">N</CODE>" format expects them in, which we use to treat the series of bits as representing a 32-bit integer.</P><PRECLASS="programlisting">$num = bin2dec('0110110'); # $num is 54$binstr = dec2bin(54); # $binstr is 110110</PRE></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch02-pgfId-361">See Also</A></H3><PCLASS="para">The <CODECLASS="literal">pack</CODE> and <CODECLASS="literal">unpack</CODE> functions in <EMCLASS="emphasis">perlfunc </EM>(1) and <ACLASS="olink"HREF="../prog/ch03_01.htm">Chapter 3</A> of <ACLASS="citetitle"HREF="../prog/index.htm"TITLE="Programming Perl"><CITECLASS="citetitle">Programming Perl</CITE></A>; we also use <CODECLASS="literal">pack</CODE> and <CODECLASS="literal">unpack</CODE> in <ACLASS="xref"HREF="ch01_05.htm"TITLE="Converting Between ASCII Characters and Values">Recipe 1.4</A>; to convert between decimal, hexadecimal, and octal, see <ACLASS="xref"HREF="ch02_17.htm"TITLE="Converting Between Octal and Hexadecimal">Recipe 2.16</A><CITECLASS="citetitle"> </CITE><ACLASS="indexterm"NAME="ch02-idx-1000008011-0"></A><ACLASS="indexterm"NAME="ch02-idx-1000008011-1"></A><ACLASS="indexterm"NAME="ch02-idx-1000008011-2"></A><ACLASS="indexterm"NAME="ch02-idx-1000008011-3"></A></P></DIV></DIV><DIVCLASS="htmlnav"><P></P><HRALIGN="LEFT"WIDTH="684"TITLE="footer"><TABLEWIDTH="684"BORDER="0"CELLSPACING="0"CELLPADDING="0"><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch02_04.htm"TITLE="2.3. Rounding Floating-Point Numbers"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 2.3. Rounding Floating-Point Numbers"BORDER="0"></A></TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><ACLASS="book"HREF="index.htm"TITLE="Perl Cookbook"><IMGSRC="../gifs/txthome.gif"ALT="Perl Cookbook"BORDER="0"></A></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch02_06.htm"TITLE="2.5. Operating on a Series of Integers"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 2.5. Operating on a Series of Integers"BORDER="0"></A></TD></TR><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228">2.3. Rounding Floating-Point Numbers</TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><ACLASS="index"HREF="index/index.htm"TITLE="Book Index"><IMGSRC="../gifs/index.gif"ALT="Book Index"BORDER="0"></A></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228">2.5. Operating on a Series of Integers</TD></TR></TABLE><HRALIGN="LEFT"WIDTH="684"TITLE="footer"><FONTSIZE="-1"></DIV<!-- LIBRARY NAV BAR --> <img src="../gifs/smnavbar.gif" usemap="#library-map" border="0" alt="Library Navigation Links"><p> <a href="copyrght.htm">Copyright © 2002</a> O'Reilly & Associates. All rights reserved.</font> </p> <map name="library-map"> <area shape="rect" coords="1,0,85,94" href="../index.htm"><area shape="rect" coords="86,1,178,103" href="../lwp/index.htm"><area shape="rect" coords="180,0,265,103" href="../lperl/index.htm"><area shape="rect" coords="267,0,353,105" href="../perlnut/index.htm"><area shape="rect" coords="354,1,446,115" href="../prog/index.htm"><area shape="rect" coords="448,0,526,132" href="../tk/index.htm"><area shape="rect" coords="528,1,615,119" href="../cookbook/index.htm"><area shape="rect" coords="617,0,690,135" href="../pxml/index.htm"></map> </BODY></HTML>
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?