Results 1 to 7 of 7

Thread: Convert int to BitArray[Resolved]

  1. #1

    Thread Starter
    Hyperactive Member GlenW's Avatar
    Join Date
    Nov 2001
    Location
    Gateshead, England
    Posts
    479

    Convert int to BitArray[Resolved]

    I want to convert an int to binary and put the binary number's bits into a BitArray.
    Anyone know how to do this?
    Last edited by GlenW; Sep 21st, 2005 at 09:32 AM.

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Convert int to BitArray

    VB Code:
    1. Dim myInteger As Integer                                        'Store integer value here.
    2.         Dim myBinaryString As String = Convert.ToString(myInteger, 2)   'Convert integer to biary string.
    3.         Dim myBitArray As New BitArray(myBinaryString.Length)           'Initialise bit array.
    4.  
    5.         'Store True for every "1" and False for every "0".
    6.         For i As Integer = 0 To myBitArray.Length - 1 Step 1
    7.             myBitArray(i) = (myBinaryString.Chars(i) = "1"c)
    8.         Next i
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Convert int to BitArray

    Oops. Let's try that again in C#:
    Code:
    int myInteger; // Store integer value here.
    string myBinaryString = Convert.ToString(myInteger, 2); // Convert integer to binary string.
    BitArray myBitArray = new BitArray(myBinaryString.Length); // Initialise bit array.
    
    // Store True for every "1" and False for every "0".
    for(int i = 0; i < myBitArray.Length; i++)
    {
        myBitArray[i] = (myBinaryString.Chars[i] == '1')
    }
    I just typed this rather than pasting from the IDE but I believe it's sound.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  4. #4
    Retired G&G Mod NoteMe's Avatar
    Join Date
    Oct 2002
    Location
    @ Opera Software
    Posts
    10,190

    Re: Convert int to BitArray

    It is nearly too tempting to post this now..

    To do it in pure IL
    Code:
    // TestILAssembler.il
    // 11.28.04 Jeff Louie
    .assembly extern mscorlib {}
    .assembly TestILAssembler {.ver 1:0:1:0}
    
    .method private static void  Main(string[] args) cil managed
    {
    	.entrypoint
    	.custom instance void [mscorlib]System.STAThreadAttribute::.ctor() = 
    		( 01 00 00 00 ) 
    	.maxstack  4
    	.locals init ([0] int32 n_counter,[1] int32 n_input)
    	 .try  // get user input
    	{
    			ldstr "Enter number: "
    			call void [mscorlib]System.Console::Write(string)
    			call string [mscorlib]System.Console::ReadLine()
    			call int32 [mscorlib]System.Int32::Parse(string)
    			// parse may throw exception
    			stloc.1  // place valid user input into n_input
          			leave.s   got_value  // leave don't branch from try
    	}  // end .try
    	catch [mscorlib]System.Object 
    	{
    		pop  	// remove exception from stack
    		ldstr    "Invalid Number."
    		call     void [mscorlib]System.Console::WriteLine(string)
    		leave    exit  // invalid input so exit program
    	}  // end handler
    
     	got_value:	ldloc.1  // push value n_input onto stack
    			dup
    			call void [mscorlib]System.Console::Write(int32)
    			ldstr " [Input value] "
    			call void [mscorlib]System.Console::WriteLine(string)
    			// **** (for int i=0; i<32; i++)  ****
    	load_counter:	ldc.i4 0  // initialize n_counter 0
    			stloc.0  // store in local variable n_count
    	begin_loop:	ldloc.0  // get current counter value
    			ldc.i4 32
    			bge end_loop  // break loop if counter is >=32
    			dup
      			ldc.i4 0x80000000  
    			// bit mask 10000000000000000000000000000000
      			and  // clear all bits except most significant
    			ldc.i4 0x80000000 
    			ceq  // push 1 if most sig bit is true, else 0
      			call void [mscorlib]System.Console::Write(int32)
    			ldc.i4 1  // push 1
      			shl  // *** shift left 1, zero least sig bit ****
    			ldloc.0  // get n_counter
    			ldc.i4 1
    			add  // add 1 to n_counter, postfix increment
    			stloc.0 // store new n_counter value
    			br begin_loop  // branch to loop again
    			// **** end for loop ****
    	end_loop:	pop  // remove input value should be all zeros
    			ldstr " [32 bit value] "
    	end_algo:	call void [mscorlib]System.Console::WriteLine(string)
    	exit:		ldstr "JAL 11.25.04"
    			call void [mscorlib]System.Console::WriteLine(string)
    			ret
    } // end of method Main
    Input/output
    Enter number: 10
    10 [Input value]
    00000000000000000000000000001010 [32 bit value]



  5. #5

    Thread Starter
    Hyperactive Member GlenW's Avatar
    Join Date
    Nov 2001
    Location
    Gateshead, England
    Posts
    479

    Re: Convert int to BitArray

    I think this is the best way
    VB Code:
    1. BitArray larrBits = new BitArray(System.BitConverter.GetBytes(123));

  6. #6
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Convert int to BitArray

    Quote Originally Posted by GlenW
    I think this is the best way
    VB Code:
    1. BitArray larrBits = new BitArray(System.BitConverter.GetBytes(123));
    I think you may be right. Way to ask a question and then make me look silly by giving a better answer yourself. I've learned something new so it was worthwhile.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  7. #7

    Thread Starter
    Hyperactive Member GlenW's Avatar
    Join Date
    Nov 2001
    Location
    Gateshead, England
    Posts
    479

    Re: Convert int to BitArray[Resolved]

    Only problem is the BitArray returned is little endian, actually this is better for me because I'm using it to save mutliple bool values in one integer in a database. Just looping through the CheckBoxes in a CheckBoxList and adding bit values to an integer. Then when you read the integer back you loop through the approriate index of the BitArray to set the CheckBoxes again. In the past I've converted integers into bit strings and used them.

    Also BitArrays don't support the reverse method so if you want a big endian BitArray you'll have to reverse it long-hand, not exactly rocket-science.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width