在这种特殊情况下: void foo(无符号输入,int *输出) { while(输入!= 0){ 如果((输入& 1)!= 0){ ++(*输出); } ++输出; 输入>> = 1; } } (这是一点点Ť ricker with signed int,因为符号可能是由右移传播的。一般来说,在处理比特时我会避免签署 类型。) - James Kanze(GABI软件)电子邮件:ja ********* @ gmail.com Conseils eninformatiqueorientéeobjet/ Beratung in objektorientierter Datenverarbeitung 9个地方Sémard,78210 St.-Cyr-l''coco,法国,+ 33(0)1 30 23 00 34In this particular case:voidfoo( unsigned input, int* output ){while ( input != 0 ) {if ( (input & 1) != 0 ) {++ (*output) ;}++ output ;input >>= 1 ;}}(It''s a bit tricker with a signed int, since the sign may bepropagated by the right shift. In general, I would avoid signedtypes when dealing with bits.)--James Kanze (GABI Software) email:ja*********@gmail.comConseils en informatique orientée objet/Beratung in objektorientierter Datenverarbeitung9 place Sémard, 78210 St.-Cyr-l''école, France, +33 (0)1 30 23 00 34 在这种特殊情况下: void foo(unsigned input,int * output) { while(input!= 0){ if((input& 1) )!= 0){ ++(*输出); } ++输出; 输入>> = 1; } } (带有符号的int有点诡计,因为符号可能是由右移传播的。一般情况下,在处理比特时我会避免使用签名的 类型。)In this particular case: void foo( unsigned input, int* output ) { while ( input != 0 ) { if ( (input & 1) != 0 ) { ++ (*output) ; } ++ output ; input >>= 1 ; } }(It''s a bit tricker with a signed int, since the sign may bepropagated by the right shift. In general, I would avoid signedtypes when dealing with bits.) 谢谢。更多地使用它,我发现声明: 如果(~input& 1)比我( 1)!= 0)快于我的 特定编译器(gnu)。看看装配输出我可以看到 为什么;虽然其他一些编译器我已经尝试过优化两个相同的机器代码 。不知道是否错过了gnu优化,或者 gnu对违反某些标准规则更加迂腐。 它也证明了更快地创建一个模板化的编译时循环,而不是带有循环条件的显式循环的。 谢谢Thanks. Playing around with it more, I found that the statement:if( ~input & 1) was faster than if( (input & 1) != 0) on myparticular compiler (gnu). Looking at the assembly output I can seewhy; although some other compilers I''ve tried optimize both to thesame machine code. Don''t know if that''s a missed gnu optimization, orgnu is just being more pedantic about violating some standards rule.It also proved faster to create a templated compile-time loop insteadof an explicit loop with a loop conditional.Thanks 这篇关于检查位的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-20 11:42
查看更多