Another way to test it would be

firstbit(n::Integer) = n != (n << 1) >> 1


This does not count negative integers. Or if you want to count negative
integers, then this does the trick:

firstbit(n::Integer) = n != (n << 1) >>> 1


For all of the above, calling this on BigInts doesn't make much sense since
they don't have a high bit, but if you did want to be able to do that,
you'd probably want to specialize it like this:

firstbit(n::BigInt) = false



On Sat, Aug 13, 2016 at 3:30 PM, Erik Schnetter <[email protected]> wrote:

> You can also write
> ```Julia
> firstbit(n::Integer) = signed(n) < 0
> ```
>
> I hope that LLVM generates the same machine code for this as for Steven's
> bit masks above. Using bit masks is more general since it allows you to
> test every bit, not just the "first" (sign) bit.
>
> -erik
>
>
> On Sat, Aug 13, 2016 at 11:10 AM, Steven G. Johnson <[email protected]
> > wrote:
>
>>
>>
>> On Saturday, August 13, 2016 at 9:22:14 AM UTC-4, jw3126 wrote:
>>>
>>> Sorry my question was confusing. What I want is a function that behaves
>>> as follows on bittypes:
>>>
>>> *0*0101101 -> 0
>>> *0*1110101 -> 0
>>> *0*1011011 -> 0
>>> *1*0011101 -> 1
>>> *1*1010001 -> 1
>>> *1*0110111 -> 1
>>>
>>
>> Normally to compute this function you would just check whether the
>> bitwise-and with 10000000 is nonzero.  e.g.
>>
>> firstbit(n::Union{UInt8,Int8}) = (n & 0x80) != 0
>> firstbit(n::Union{UInt16,Int16}) = (n & 0x8000) != 0
>> firstbit(n::Union{UInt32,Int32}) = (n & 0x80000000) != 0
>> firstbit(n::Union{UInt64,Int64}) = (n & 0x8000000000000000) != 0
>> firstbit(n::Union{UInt128,Int128}) = (n & 0x80000000000000000000000000000000)
>> != 0
>> firstbit(n::Integer) = leading_ones(n) > 0
>>
>
>
>
> --
> Erik Schnetter <[email protected]> http://www.perimeterinstitute.
> ca/personal/eschnetter/
>

Reply via email to