Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   Java (http://www.programmingforums.org/forum17.html)
-   -   String of bits to byte[] (http://www.programmingforums.org/showthread.php?t=15325)

hbe02 Mar 5th, 2008 9:46 AM

String of bits to byte[]
 
how can i convert a string of bit String S = "01010101010101010101"
into a byte b[]
dont worry about left over bits.. assume that the size of S is a multiple of 8-bits

Sane Mar 5th, 2008 10:07 AM

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 ...



All times are GMT -5. The time now is 12:53 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC