开发者

If a language has no "bit to bit" comparison, how do I simulate it?

I'm trying to make a script in the (beta) Trackmania 2 game. (It's an ugly kindof mix between JavaScript, HTML, C, and... other stuff I couldn't imagine in my worst nightmare).

The scripting engine doesn't seem to know the "and" or "&&" (if I try myVar && 16 the nice error raised is "boolean operation awaits a boolean")

I'd like to do something like:

if (Var && 1) {
  // Bit North => trace north
}

if (Var && 2) {
  // Bit East => trace east
}
if (Var && 4) {
  // Bit South => trace south
}
if (Var && 8) {
  // Bit West => trace West
}

开发者_如何学JAVAAny idea how I could do this if the compiler doesn't know bitfield operations?


"Bitwise and" is usually &, not &&. (&& is usually a "logical and".) "Bitwise and" is & in C and JavaScript, two languages you mentioned. In fact, && appears to be "logical and" bassd on the error message you got. The solution might simply be to use

if (Var & 1)

If you really don't have bitwise ops, it can still be done. Keep in mind that a 4 bit number can be expressed as:

b3 * 2**3 + b2 * 2**2 + b1 * 2**1 + b0 * 2**0

If you have exponentiation, division, integer truncation and modulus, you could use the following to see if to find out if bit x is set:

int( i / (2**x) ) % 2

If you don't have exponentiation, it can be replaced with a lookup table.

If you don't have modulus, i % 2 can be replaced with ( (i/2) - int(i/2) )*2

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜