Click here to Skip to main content
15,898,588 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
See more:
I want to get the index of the first bit that equal to 1, and the index of the last bit that equal to 1. For example:

data=0x3E

first bit = 1

last bit = 5

How can I do this?
Posted
Comments
Andreas Gieriet 13-Feb-14 16:44pm    
Have you already tried something? E.g. probing? What you need is shifting and bit-and (and counting).
Cheers
Andi
Member 10304617 13-Feb-14 16:47pm    
first and last bit that turn on

1 solution

Pseudo code:
function get_lowest_bit(in input, out bit_pos) returns true if input is not 0, false otherwise
  for bit_pos = 0 to max_bits-1
    if (input bit_and (1 left_shift bit_pos) not_equal 0
       return true
    end if
  end for
  return false
end function


Likewise for the upper bit.
Cheers
Andi
PS: I assume this is a homework, that's why I do not give you the C# solution and leave the exercise for the highest bit for you ;-)
 
Share this answer
 
v2
Comments
Member 10304617 13-Feb-14 16:56pm    
sorry, but i did not understand the code.
what is max_bit?
and what do you ask in the if()...?
Andreas Gieriet 13-Feb-14 17:44pm    
I think you have to figure out that yourself. Requires basic understanding of C# types. E.g. if the type of your variable is int, replace max_bits by the number of bits for type int. The terms bit_and, left_shift, not_equal can be looked up in your text book or in google. How to write a for-loop, a function, and an if-statement is also basic C# knowledge that will not be explained here by anyone.
Cheers
Andi
Member 10304617 13-Feb-14 18:27pm    
I know C# very well.
Andreas Gieriet 13-Feb-14 18:29pm    
Hm, then I wonder why the question...
Anyways, seems you get it done somehow, then.
Cheers
Andi
Sergey Alexandrovich Kryukov 13-Feb-14 17:21pm    
5ed... :-)
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900