Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old Mar 5th, 2008, 9:46 AM   #1
hbe02
Hobbyist Programmer
 
hbe02's Avatar
 
Join Date: Mar 2006
Location: Lebanon
Posts: 148
Rep Power: 3 hbe02 is on a distinguished road
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
hbe02 is offline   Reply With Quote
Old Mar 5th, 2008, 10:07 AM   #2
Sane
Programming Guru
 
Sane's Avatar
 
Join Date: Apr 2005
Posts: 1,827
Rep Power: 5 Sane will become famous soon enough
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
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
An Attempt at a DBMS grimpirate PHP 8 Apr 17th, 2007 1:01 PM
Throwing an exception when using string constructor csrocker101 C# 3 Apr 8th, 2007 2:04 PM
Help with breaking apart a string csrocker101 C# 6 Apr 6th, 2007 7:50 AM
Function Parameters grimpirate PHP 10 Mar 14th, 2007 6:55 PM
Problems with String to MD5 Conversion emdiesse Visual Basic .NET 0 Feb 2nd, 2006 10:25 AM




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 11:33 AM.

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