尾随/前导零计数为一个字节 [英] Trailing/leading zero count for a byte

查看:89
本文介绍了尾随/前导零计数为一个字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Java,并且正在编写国际象棋引擎.

I'm using Java and I'm coding a chess engine.

我正在尝试查找字节中前1位的索引和后1位的索引.

I'm trying to find the index of the first 1 bit and the index of the last 1 bit in a byte.

我目前在Java中使用Long.numberOfTrailingZeros()(或类似的东西),并且希望模拟该功能,但字节除外.

I'm currently using Long.numberOfTrailingZeros() (or something like that) in Java, and would like to emulate that functionality, except with bytes.

会是这样吗?

byte b = 0b011000101;
int firstOneBit = bitCount ((b & -b) - 1);

如果是这样,我将如何相对有效地实现bitCount.我不介意解释,请不要只给我代码.

If so, how would I implement bitCount relatively efficiently. I don't mind good explainations, please don't just give me code.

推荐答案

使用具有256个条目的查找表. 创建它:

use a lookup tabel with 256 entries. to create it:

unsigned int bitcount ( unsigned int i ) {
unsigned int r = 0;
while ( i ) { r+=i&1; i>>=1; } /* bit shift is >>> in java afair */
return r; 
}

这当然不需要太快,因为您最多可以执行256次来初始化表格.

this of course does not need to be fast as you do it at most 256 times to init your tabel.

这篇关于尾随/前导零计数为一个字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆