kejpa Posted June 23, 2004 Posted June 23, 2004 Hey there How do you get the value of a bitarray. Not the individual items but of the whole array? After setting the individual bits I want the value of the the array Dim baParameter As New BitArray(7) baParameter.Set(3,True) baParameter.Set(5,True) baParameter.Set(2,True) baParameter.Set(1,True) Dim i as Integer=baParameter.value ' Don't work! At the end of this snippet I want to have i = 46 (2^5+2^3+2^2+2^2) Regards /Kejpa Quote
pelikan Posted June 23, 2004 Posted June 23, 2004 .value??? no such animal but all problems except you know what have a solution Public Function SumBits(ByVal ba As BitArray) As Integer Dim accum As Double = 0.0 Dim i As Integer For i = 0 To ba.Count - 1 If ba(i) Then accum += 2 ^ i End If Next Return CInt(accum) End Function Quote IN PARVUM MULTUM
kejpa Posted June 24, 2004 Author Posted June 24, 2004 :) I know there's no such animal but what I can't figure out is why Noah never brought it onboard. I've solved it the same way you suggested but I thought there were a handier way. /Kejpa Quote
*Experts* Nerseus Posted June 24, 2004 *Experts* Posted June 24, 2004 If your endgoal is to get this as an int, I'd suggest using BitVector32 (part of System.Collections.Specialized). It's faster and easier to use, mostly. I don't know if there's a handier way of converting a BitArray into an int than the manual looping approach you mention. You might be able to use CopyTo to get the bits into a different array and then convert that array into an int, but that seems like almost as much work. -nerseus Quote "I want to stand as close to the edge as I can without going over. Out on the edge you see all the kinds of things you can't see from the center." - Kurt Vonnegut
kejpa Posted June 28, 2004 Author Posted June 28, 2004 BitVector32 simple?!? If your endgoal is to get this as an int' date=' I'd suggest using BitVector32 [/quote'] Maybe not endgoal, but something to use along the way, yes. It's faster and easier to use' date=' mostly.[/quote'] Faster, so they say. Easier, I've heard that too, didn't believe it then either, later proved me right ;) Challange: Set 8 bits and return value. This is the way I would like it done, but it's not working, returns 7 instead of 255 Dim bv As System.Collections.Specialized.BitVector32 bv.Item(0) = 1 bv.Item(1) = 1 bv.Item(2) = 1 bv.Item(3) = 1 bv.Item(4) = 1 bv.Item(5) = 1 bv.Item(6) = 1 bv.Item(7) = 1 MsgBox(bv.Data) Regards /Kejpa Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.