|
-
Apr 3rd, 2003, 09:46 AM
#1
Thread Starter
Frenzied Member
>3 bits set in byte
I need to write a function:
f( b As Byte ) As Boolean
The function must return True if the value of b has 3 or less bits set. Otherwise, f returns False.
I can achieve this by converting b to a string using binary format then counting the number of '1's in the string, but I'd like to know if there's a more elegant way to do it.
Anyone care to have a go?
This world is not my home. I'm just passing through.
-
Apr 3rd, 2003, 10:58 AM
#2
New Member
Not elegant but can be done in a single line if you know how to translate this from C++ to VB (I don't know)
Code:
if (((b>>7)&1+(b>>6)&1+(b>>5)&1+(b>>4)&1+(b>>3)&1+(b>>2)&1+(b>>1)&1+b&1)<=3) return TRUE;
else
return FALSE;
-
Apr 3rd, 2003, 01:26 PM
#3
Fanatic Member
VB Code:
Function f(b As Byte) As Boolean
If ((b \ 128) and 1) + ((b \ 64) and 1) + ((b \ 32) and 1) + ((b \ 16) and 1) + ((b \ 8) and 1) + ((b \ 4) and 1) + ((b \ 2) and 1) + (b and 1) <= 3 then
f = True
Else
f = False
End If
End Function
This should work I think
-
Apr 3rd, 2003, 09:02 PM
#4
Fanatic Member
hmm....
you are testing a boolean statement and if true, you return true, if false, u return false. Why not just return the statement:
VB Code:
Function f(b As Byte) As Boolean
f=((((b \ 128) and 1) + ((b \ 64) and 1) + ((b \ 32) and 1) + ((b \ 16) and 1) + ((b \ 8) and 1) + ((b \ 4) and 1) + ((b \ 2) and 1) + (b and 1)) <= 3)
End Function
Hopefully this should work
sql_lall 
-
Apr 3rd, 2003, 10:21 PM
#5
Fanatic Member
private function BOOLINGWOOOO(byval b as byte)
dim a as byte 'loop variable
dim c as byte 'number of rights
For a = 7 to 0 step -1
if 2^a > b then c = c + 1: b = b - 2^a
next a
^untested, so not sure.
Don't pay attention to this signature, it's contradictory.
-
Apr 4th, 2003, 01:48 AM
#6
Fanatic Member
Re: hmm....
Originally posted by sql_lall
you are testing a boolean statement and if true, you return true, if false, u return false.
I know, but I wanted to stay in the same line as Dr. Luz.
-
Apr 4th, 2003, 02:44 AM
#7
Thread Starter
Frenzied Member
Thanks to all - these look a lot nicer than my string manipulation.
This world is not my home. I'm just passing through.
-
Apr 5th, 2003, 05:54 PM
#8
transcendental analytic
fast and elegant way:
y=0!=x&=(x-1);
y+=0!=x&=(x-1);
y+=0!=x&=(x-1);
y+=0!=x&=(x-1);
return y<4;
Use  
writing software in C++ is like driving rivets into steel beam with a toothpick.
writing haskell makes your life easier:
reverse (p (6*9)) where p x|x==0=""|True=chr (48+z): p y where (y,z)=divMod x 13
To throw away OOP for low level languages is myopia, to keep OOP is hyperopia. To throw away OOP for a high level language is insight.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|