⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 faqcat38c2.html

📁 this is a mirrored site c-faq. thought might need offline
💻 HTML
📖 第 1 页 / 共 5 页
字号:
<p>References:PCS Sec. 11 p. 179<hr><hr><hr><a name="hexio"><h1>comp.lang.c FAQ list<font color=blue>&middot;</font><a href="../../misc/hexio.html"><!-- qtag -->Question 20.10</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>How can I convert integers tobinary orhexadecimal?</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>Make sure you really know what you're asking.Integers are stored internally in binary,although for most purposes it is not incorrectto think of them as being inoctal, decimal, or hexadecimal,whichever is convenient.The base in which a number is expressed matters only when thatnumber is read in from or written out to the outside world,either in the form ofa source code constantor in the form of I/Operformed by a program.</p><p>In source code,a non-decimal base is indicatedbya leading <TT>0</TT> or <TT>0x</TT>(for octal or hexadecimal, respectively).During I/O, the base of a formatted number is controlledin the<TT>printf</TT>and <TT>scanf</TT>familyof functionsby the choice of format specifier(<TT>%d</TT>, <TT>%o</TT>, <TT>%x</TT>, etc.)and in the <TT>strtol</TT>and <TT>strtoul</TT>functionsby the third argument.During<em>binary</em> I/O,however, the base again becomes immaterial:if numbers are being read or written as individual bytes(typically with <TT>getc</TT> or <TT>putc</TT>),or as multi-byte words(typically with <TT>fread</TT> or <TT>fwrite</TT>),it is meaningless to ask what ``base'' they are in.</p><p>If what you need is formatted binary conversion,it's easy enough to do.Here is a little functionfor formattinga number in a requested base:<pre>char *baseconv(unsigned int num, int base){	static char retbuf[33];	char *p;	if(base &lt; 2 || base &gt; 16)		return NULL;	p = &amp;retbuf[sizeof(retbuf)-1];	*p = '\0';	do {		*--p = "0123456789abcdef"[num % base];		num /= base;	} while(num != 0);	return p;}</pre>(Note that this function, as written,returns a pointer to static data,such that only one of its return values can be used at a time;see question <a href="faqcatbafd.html?sec=malloc#retaggr">7.5a</a>.A better size for the <TT>retbuf</TT> arraywould be <TT>sizeof(int)*CHAR_BIT+1</TT>;see question <a href="faqcat1d60.html?sec=stdio#sprintfsize">12.21</a>.)</p><p>For more information about ``binary'' I/O,seequestions <a href="faqcat6b6b.html?sec=struct#io">2.11</a>, <a href="faqcat1d60.html?sec=stdio#binaryio">12.37</a>, and <a href="faqcat1d60.html?sec=stdio#extconform">12.42</a>.See also questions<a href="faqcate107.html?sec=charstring#asciivals">8.6</a>and<a href="faqcat1067.html?sec=lib#itoa">13.1</a>.</p><p>Additional links:A<a href="faqcat38c2.html?sec=misc#btod">long reply</a>I sent to someone who was asking how to write a``binary to decimal'' conversion function</p><p>References:ISO Secs. 7.10.1.5,7.10.1.6<hr><hr><hr><a name="base2"><h1>comp.lang.c FAQ list<font color=blue>&middot;</font><a href="../../misc/base2.html"><!-- qtag -->Question 20.11</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>Can I use base-2 constants(something like <TT>0b101010</TT>)?<br>Is there a<TT>printf</TT> format for binary?</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>No, on both counts,although there are various preprocessor tricks you can try(see the links below).You can convert base-2 string representationsto integers with <TT>strtol</TT>.If you need to print numbers out in base 2,seethe example code inquestion <a href="faqcat38c2.html?sec=misc#hexio">20.10</a>.</p><p>Additional links:<br><br><a href="http://home.att.net/~jackklein/ctips01.html#binary_in">example by Jack Klein</a><br><br><a href="../../misc/sd27.html" rel=subdocument>preprocessor trick</a>by Karl Heuer<br><br><a href="../../misc/sd28.html" rel=subdocument>prettier preprocessor trick</a>by Bill Finke<hr><hr><hr><a name="bitcount"><h1>comp.lang.c FAQ list<font color=blue>&middot;</font><a href="../../misc/bitcount.html"><!-- qtag -->Question 20.12</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>What is the most efficient way to count the number of bitswhich are set inan integer?</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>Many ``bit-fiddling'' problemslike this onecan besped up and streamlined usinglookup tables(but seequestion <a href="faqcat38c2.html?sec=misc#efficiency">20.13</a>).Here is a little function which computes the number of bits in a value,4 bits at a time:<pre>static int bitcounts[] =	{0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4};int bitcount(unsigned int u){	int n = 0;	for(; u != 0; u &gt;&gt;= 4)		n += bitcounts[u &amp; 0x0f];	return n;}</pre><hr><hr><hr><a name="efficiency"><h1>comp.lang.c FAQ list<font color=blue>&middot;</font><a href="../../misc/efficiency.html"><!-- qtag -->Question 20.13</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>What's the best way of making my program efficient?</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>By picking good algorithms,implementing them carefully,and making sure that your program isn't doing any extra work.For example,the most microoptimized character-copying loop in the worldwill be beat by code which avoids having to copy characters at all.</p><p>When worrying about efficiency,it's important to keep several things in perspective.First of all,although efficiency isan enormously populartopic,itis notalways as importantas people tend to think it is.Most of the code in most programs is not time-critical.When code is not time-critical,it isusuallymore important that it be written clearly and portablythan that it be written maximally efficiently.(Remember thatcomputers are very, very fast,and that seemingly ``inefficient'' codemay be quite efficiently compilable,andrun without apparent delay.)</p><p>It is notoriously difficult to predictwhatthe ``hot spots'' in a program will be.When efficiency is a concern,it is important to use profiling softwareto determine which parts of the program deserve attention.Often, actual computation time is swamped by peripheral taskssuch as I/O and memory allocation,which can be sped up by using buffering and cachingtechniques.</p><p>Evenforcode that <em>is</em> time-critical,one of the least effective optimization techniquesis to fuss withthe coding details.Many of the ``efficient coding tricks''which are frequently suggestedare performed automaticallyby evensimplemindedcompilers.Heavyhanded optimization attempts can make code sobulky that performance is actually degraded,by increasing the number of page faults orbyoverflowing instruction caches or pipelines.Furthermore,optimization tricksare rarely portable(i.e. they may speed things up on one machinebut slow them down on another).In any case,tweaking the coding usually results inat best linear performance improvements;the big payoffs are in betteralgorithms.</p><p>If the performance of your code is so importantthat you are willing to invest programming timein source-level optimizations,make sure that you are usingthe best optimizing compileryou can afford.(Compilers,even mediocre ones,can perform optimizationsthat are impossible at the source level).</p><p>When efficiency is trulyimportant,the best algorithm has been chosen,and even the coding details matter,the following suggestions may be useful.(These are mentioned merelyto keep followups down;appearance here does<em>not</em>necessarilyconstitute endorsement by the author.Note that several of these techniquescut both ways,andmay make things worse.)<OL><li>Sprinkle the code liberally with <TT>register</TT> declarations foroft-used variables;place them in inner blocks,if applicable.(On the other hand, most modern compilers ignore <TT>register</TT>declarations, on the assumption that they can perform register analysis and assignment better than the programmer can.)<li>Check the algorithm carefully.Exploit symmetries where possible to reduce the number of explicit cases.<li>Examine the control flow:make sure that common cases are checked for first,and handled more easily.If one side ofan expression involving <TT>&amp;&amp;</TT> or <TT>||</TT>will usually determine the outcome,make it the left-hand side,if possible.(See also question <a href="faqcatee08.html?sec=expr#shortcircuit">3.6</a>.)<li>Use <TT>memcpy</TT> instead of<TT>memmove</TT>,if appropriate(see question<a href="faqcat7d4b.html?sec=ansi#memmove">11.25</a>).<li>Use machine- and vendor-specific routines and <TT>#pragma</TT>s.<li>Manually placecommon subexpressionsin temporary variables.(Good compilers do this for you.)<li>Move critical, inner-loop codeout of functionsand into macros or in-line functions(and out of the loop, if invariant).If the termination condition of a loop is a complexbut loop-invariantexpression,precompute it and place it in a temporary variable.(Good compilers do these for you.)<li>Change recursion to iteration, if possible.<li>Unroll small loops.<li>Discover whether<TT>while</TT>, <TT>for</TT>,or <TT>do/while</TT>loops produce the best code under your compiler,and whether incrementing or decrementingthe loop control variableworks best.<li>Remove <TT>goto</TT> statements--some compilers can't optimize as well in their presence.<li>Use pointers rather than array subscripts to step through arrays(but see question <a href="faqcat38c2.html?sec=misc#eff2">20.14</a>).<li>Reduce precision.(Using <TT>float</TT> instead of <TT>double</TT>may result in faster,single-precision arithmetic under an ANSI compiler,thougholder compilers convert everything to <TT>double</TT>,so using <TT>float</TT> can also be slower.)Replace time-consuming trigonometric and logarithmic functionswith your own,tailored to the range and precision you need,and perhaps using table lookup.(Be sure to give your versions<em>different</em>names;see question <a href="faqcatd3c2.html?sec=decl#namespace">1.29</a>.)<li>Cache or precomputetables of frequently-needed values.(See also question <a href="faqcat38c2.html?sec=misc#bitcount">20.12</a>.)<li>Use standard library functions in preference to your own.(Sometimes the compilerinlines orspecially optimizesits own functions.)On the other hand,if your program's calling patterns areparticularly regular,your own special-purpose implementation may be able to beatthe library's general-purpose version.(Again, if you do write your own version,give it a different name.)<li>As a last,<em>last</em>resort, hand-code critical routines in assembly language(or hand-tune the compiler's assembly language output).Use <TT>asm</TT> directives, if possible.</OL></p><p>Here are some things <em>not</em> to worry about:<OL><li>17x.whether <TT>i++</TT> is faster than <TT>i&nbsp;=&nbsp;i&nbsp;+&nbsp;1</TT><li>18x.whether <TT>i&nbsp;&lt;&lt;&nbsp;1</TT>(or <TT>i&nbsp;&gt;&gt;&nbsp;1</TT>, or <TT>i&nbsp;&amp;&nbsp;1</TT>)is faster than <TT>i&nbsp;*&nbsp;2</TT>(respectively <TT>i&nbsp;/&nbsp;2</TT>, <TT>i&nbsp;%&nbsp;2</TT>).</OL></p><p>(These are examples of optimizations which compilers regularly perform for you;see questions <a href="faqcat38c2.html?sec=misc#eff2">20.14</a>and <a href="faqcat38c2.html?sec=misc#shifts">20.15</a>.)</p><p>It is not the intent here to suggest that efficiency can becompletely ignored.Most of the time,however,by simply paying attention to good algorithm choices,implementing themcleanly,and avoiding obviously inefficient blunders(i.e. make sure you don't end up with anO(n**3)implementation of anO(n**2)algorithm),perfectly acceptable results can be achieved.</p><p>For more discussion of efficiency tradeoffs,as well as good advice on how to improve efficiency when it is important,seechapter 7 of Kernighan and Plauger's<I>The Elements of Programming Style</I>,and Jon Bentley's<I>Writing Efficient Programs</I>.</p><p>See also question <a href="faqcataae2.html?sec=style#vsefficiency">17.11</a>.<hr><hr><hr><a name="eff2"><h1>comp.lang.c FAQ list<font color=blue>&middot;</font><a href="../../misc/eff2.html"><!-- qtag -->Question 20.14</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>Are pointers really faster than arrays?How much do function calls slow things down?Is <TT>++i</TT> faster than <TT>i&nbsp;=&nbsp;i&nbsp;+&nbsp;1</TT>?</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>Precise answers to these and many similar questionsdependof courseon the processor and compiler in use.If you simply must know,you'll have to time test programs carefully.(Often the differences are so slight thathundreds ofthousands of iterations are required even to see them.<a href="../../misc/subtle.html" rel=subdocument>[footnote]</a>Check the compiler's assembly language output,if available,to see if twopurported alternatives aren't compiled identically.)</p><p>For conventional machines,it is usuallyfaster to march through large arrays withpointers rather than array subscripts,but for some processors the reverse is true.(Better compilers shouldgenerate good coderegardless of which notation you use,thoughit's arguably easier for a compilerto convert array indices to pointers than vice versa<a href="../../misc/fn98.html" rel=subdocument>[footnote]</a>.)</p><p>Function calls,though obviously incrementally slower than in-line code,contribute so much to modularity and code claritythat there is rarely good reason to avoid them.(Actually, by reducing bulk,functions can improve performance.)Also,some compilers are able to expandsmall, critical-path functionsin-line,either as an optimization or at the programmer's request.</p><p>Before rearranging expressions such as <TT>i&nbsp;=&nbsp;i&nbsp;+&nbsp;1</TT>,remember that you are dealing with a compiler,not a keystroke-programmable calculator.Any decent compilerwill generate identical code for <TT>++i</TT>, <TT>i&nbsp;+=&nbsp;1</TT>,and <TT>i&nbsp;=&nbsp;i&nbsp;+&nbsp;1</TT>.The reasons for using <TT>++i</TT> or <TT>i&nbsp;+=&nbsp;1</TT> over <TT>i&nbsp;=&nbsp;i&nbsp;+&nbsp;1</TT>have to do with style, not efficiency.(See also question<a href="faqcatee08.html?sec=expr#plusplus">3.12b</a>.)<hr><hr><hr><a name="shifts"><h1>comp.lang.c FAQ list<font color=blue>&middot;</font><a href="../../misc/shifts.html"><!-- qtag -->Question 20.15</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>I've been replacing multiplications and divisionswith shift operators,

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -