取决于你所说的更简单。您可以使用查找表,即具有256个元素的数组(假设您的字节长度为8位),其中存储索引1 0的索引,索引2 1,索引4 2等。现在使用你的字节作为索引,你得到位置。通过在所有未使用的插槽中放置一个大于7的数字,您甚至可以检查是否真的只有一个位设置在该字节中... Depends on what you call "simpler". You could use a lookup table, i.e. an array with 256 elements (assuming your byte is 8 bits long) where at index 1 0 is stored, at index 2 1, at index 4 2 etc. Now use your byte as the index and you get the bit position. By putting a number larger than 7 into all unused slots you even have a simple and fast check if there''s really only a single bit set in that byte... 这显然是一种非常快速的技术,但请记住 a一些实现有一个CHAR_BIT事物表明 超过8位一个char。 char传统上使用 来表示一个8位字节,但它可能在 Deathstation实现上有所不同。您可能希望使用unsigned char来限定 确保值不是 符号扩展时提升为int来索引数组。 因此,你可能不得不使用屏蔽和转向强制 为256位数组索引的8位值。 如果你想隔离最右边的1位,你可以 使用类似(假设TWOS-COMPLEMENT表示): signed int foo = 12; signed int right_bit_of_foo =(foo& ; -foo); / *这是4 * / 当使用二进制补码实现时(即,不是a死亡站实现),按位和整数 ,其二进制补码隔离最右边的1位。 从那里,您可以使用移位和屏蔽找到 最右边的非零8位值,用于索引数组。 2美分。您的里程可能会有所不同。 - --------------------------- - Jeffrey D. Smith Farsight Systems Corporation 24 BURLINGTON DRIVE LONGMONT,CO 80501-6906 http://www.farsight-systems.com z / Debug调试在IBM z / OS上运行的Systems / C程序! ISV升级费用是否过高?检查我们的定制产品开发!That is clearly a very fast technique, but remember thata some implementations have a CHAR_BIT thing that indicatesmore than 8 bits in a "char". A "char" is traditionally usedto represent an 8-bit byte, but it may be different on aDeathstation implementation. You will likely want to qualifywith "unsigned char" to be sure that the value is notsign-extended when promoted to an int for indexing the array.Thus, you may have to use masking and shifting to forcean 8-bit value for the 256-element array index.If you want to isolate the rightmost 1 bit, you coulduse something like (ASSUMING TWOS-COMPLEMENT representation):signed int foo = 12;signed int right_bit_of_foo = (foo & -foo); /* this is 4 */When using a twos-complement implementation (i.e., nota Deathstation implementation), bit-wise AND of an integerwith its twos-complement isolates the rightmost 1 bit.From there, you can use shifting and masking to find therightmost nonzero 8-bit value for indexing into the array.2 cents worth. Your mileage may vary.------------------------------Jeffrey D. SmithFarsight Systems Corporation24 BURLINGTON DRIVELONGMONT, CO 80501-6906 http://www.farsight-systems.comz/Debug debugs your Systems/C programs running on IBM z/OS!Are ISV upgrade fees too high? Check our custom product development! 这篇关于清洁方法读取位位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 09-05 13:32