View Single Post
Old Mar 5th, 2008, 10:07 AM   #2
Sane
Programming Guru
 
Sane's Avatar
 
Join Date: Apr 2005
Location: Waterloo, Ontario
Posts: 1,888
Rep Power: 5 Sane will become famous soon enough
Send a message via MSN to Sane
Re: String of bits to byte[]

Start with a byte of 0. Traverse each character from left to right, shifting the byte left with << 1. Each time you encounter a bit that's 1, set the first bit with | 1.

Do this for each grouping of 8 bits to get your byte[].

For example, given the string "01010101010101010101":

Byte       Operation       String During Iteration
--------------------------------------------------
0         (Shift << 1)        01010101010101010101
0         (Don't Set )     
0         (Shift << 1)         1010101010101010101
1         (Set    | 1)      
10        (Shift << 1)          010101010101010101
10        (Don't Set )       
100       (Shift << 1)           10101010101010101
101       (Set    | 1)        
1010      (Shift << 1)            0101010101010101
1010      (Don't Set )         
10100     (Shift << 1)             101010101010101
10101     (Set    | 1)

Etc etc ...
Sane is offline   Reply With Quote