简体   繁体   English

C中的Bit Hack无法理解

[英]Bit Hack in C Cannot Understand

I was asked this question in an interview and still cannot figure out what it does. 我在接受采访时被问到这个问题,但仍无法弄清楚它的作用。 Can someone explain what it does and how it does it? 有人可以解释它的作用以及它是如何做到的吗?

v = v - ((v >> 1) & (T)~(T)0/3);                           // temp
v = (v & (T)~(T)0/15*3) + ((v >> 2) & (T)~(T)0/15*3);      // temp
v = (v + (v >> 4)) & (T)~(T)0/255*15;                      // temp
c = (T)(v * ((T)~(T)0/255)) >> (sizeof(T) - 1) * CHAR_BIT; // count

It is explained here: 这里解释如下:

http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel

Counting bits set, in parallel 计数位并行设置

A generalization of the best bit counting method to integers of bit-widths upto 128 (parameterized by type T) is this: 将最佳位计数方法推广到位宽高达128的整数(由类型T参数化)是这样的:

v = v - ((v >> 1) & (T)~(T)0/3);                           // temp
v = (v & (T)~(T)0/15*3) + ((v >> 2) & (T)~(T)0/15*3);      // temp
v = (v + (v >> 4)) & (T)~(T)0/255*15;                      // temp
c = (T)(v * ((T)~(T)0/255)) >> (sizeof(T) - 1) * CHAR_BIT; // count

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM