Please explain behavior of setBit

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

Please explain behavior of setBit

Murray Gross

Here is my trivial program:


import Bits

main = putStr (show(bit 0::Int)++"  "++show (mybit 0))

mybit:: Int -> Int
mybit x = setBit (bit 0) x



The output (with GHC-5) is

1  1

My question: Why is (bit 0) equal to 1 and not 0? That first bit is set
regardless of the value of x (I have tried several), although in each
case, the bit I expect to be set is also set (e.g., mybit 4 yields 17).

Thanks in advance for assistance.

Murray Gross


_______________________________________________
Haskell-Cafe mailing list
[hidden email]
http://www.haskell.org/mailman/listinfo/haskell-cafe
Reply | Threaded
Open this post in threaded view
|

Re: Please explain behavior of setBit

Lemmih
On 11/13/05, Murray Gross <[hidden email]> wrote:

>
> Here is my trivial program:
>
>
> import Bits
>
> main = putStr (show(bit 0::Int)++"  "++show (mybit 0))
>
> mybit:: Int -> Int
> mybit x = setBit (bit 0) x
>
>
>
> The output (with GHC-5) is
>
> 1  1
>
> My question: Why is (bit 0) equal to 1 and not 0?

If only the first bit in an Integer is set then the number is equal to 1.

> That first bit is set
> regardless of the value of x (I have tried several), although in each
> case, the bit I expect to be set is also set (e.g., mybit 4 yields 17).

http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Bits.html

'setBit (bit 0) 4' => 'setBit 1 4' => (binary) 10001 => (dec) 17
You're setting the fifth bit in '1' instead of setting the seconded bit in '4'.

--
Friendly,
  Lemmih
_______________________________________________
Haskell-Cafe mailing list
[hidden email]
http://www.haskell.org/mailman/listinfo/haskell-cafe
Reply | Threaded
Open this post in threaded view
|

Re: Please explain behavior of setBit

Murray Gross


On Sun, 13 Nov 2005, Lemmih wrote:

>
> 'setBit (bit 0) 4' => 'setBit 1 4' => (binary) 10001 => (dec) 17

OK, what you are saying is that I have misinterpreted the behavior of bit,
which I thought only did a conversion, but in fact sets the zero-th
bit of a bit string. I have checked that this is in fact what is
happening. The (now solved) problem is obscure documentation.

Thank you.

Murray Gross

_______________________________________________
Haskell-Cafe mailing list
[hidden email]
http://www.haskell.org/mailman/listinfo/haskell-cafe