In Nimrod, what is the syntax for bitwise operations?
Asked Answered
L

2

9

I'm just discovering Nimrod and have a basic question (couldn't find the answer in the documentation).

How do you use bitwise operations ? I have the following code, where x is defined as an int :

if x and 1:

This does not compile :

Error: type mismatch: got (range 0..1(int)) but expected 'bool'

And if I try:

if and(x, 1)

I get

Error: type mismatch: got (tuple[int, int])
but expected one of:  
system.and(x: int16, y: int16): int16
system.and(x: int64, y: int64): int64
system.and(x: int32, y: int32): int32
system.and(x: int, y: int): int
system.and(x: bool, y: bool): bool
system.and(x: int8, y: int8): int8

What's the trick ?

Lightning answered 1/11, 2013 at 16:58 Comment(0)
T
10

and does bitwise and; the issue is rather that if expects a bool, not an integer. If you want C-like comparison to 0, simply add it:

>>> if 1:
...   echo("hello")
...
stdin(10, 4) Error: type mismatch: got (int literal(1)) but expected 'bool'
>>> if 1!=0:
...   echo("hello")
...
hello
Trelliswork answered 1/11, 2013 at 18:47 Comment(2)
No, I really need to perform a bitwise-and on my variable ; more precisely, here, I want to check whether the last bit is set or not.Lightning
So use (x and 1) != 0?Trelliswork
M
0

If you want to check the last bit you can use testBit from the bitops module:

import bitops
if testBit(x, 0):
  echo "Last bit is 1"
Malherbe answered 16/7, 2019 at 16:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.