我如何以更优化的方式提取出位? [英] How do I extract a bit in a more optimal way?

查看:241
本文介绍了我如何以更优化的方式提取出位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我有一个采访中,他们让我写两个C功能,一来提取单个位和其他从一个字符提取范围位。我花了一段时间,这些方法出现了。

I had a interview today where they asked me to write two "C" functions, one to to extract a single bit and other to extract a range of bits from a character. I took a while and came up with these methods.

int extractBit(char byte, int pos) {
    assert( (pos >= 0) && (pos < 8) );
    return ( ( byte & (1<<pos) ) >> pos);
}
char extractBitRange(char byte, int startingPos, int offset) {
   assert( ( (startingPos + offset) >= 0) && ( (startingPos + offset) < 8) );
   return ( byte >> startingPos ) & ~(0xff << (offset + 1));
}

但面试官一直问我,如果我能进一步加快code(CPU周期而言),如果有优化,我可以做些什么来实现它的任何范围。
我显然是不舒服的,我很想知道你会怎么做呢?

But the interviewer kept asking me if I could speed up the code further (in terms of cpu cycles) and if there is any scope of optimization that I could do to achieve it. I was clearly out of sorts and I am curious to know how would you do this?

推荐答案

在extractBit,如果你转移首先,你可以用 1 掩盖而不是(1 LT;&LT; POS)
考虑到POS是函数的参数,即节省了计算。

In extractBit, if you shift first, you can mask with 1 instead of (1<<pos). Considering that pos is an argument of the function, that saves a computation.

收益率(字节&GT;&GT; POS)及1;

在第二个功能,我就断言, startingPos 偏移都是正的,而不是声称,他们的总和是积极的,更有意义的方式。

In the second function, I would assert that startingPos and offset are both positive instead of asserting that their sum is positive, it makes more sense that way.

这篇关于我如何以更优化的方式提取出位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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