Thread: binary to ascii

  1. #1
    Just because ygfperson's Avatar
    Join Date
    Jan 2002
    Posts
    2,490

    binary to ascii

    Code:
    string to_string() {
        string temp;
        unsigned char x=0;
        for (int i=0;i<bitt.size();i++) {
          if (i%8==0 && i!=0) { temp+=x; x=0; }
          if (bitt[i])
    	    x |= (unsigned char)pow(2,i);
          if (bitt[i]==0)
    	    x &= ~(unsigned char)pow(2,i);
        }
        temp+=x;
        return temp;
      }
    bitt is a vector array of bools. i know they're non-standard (could anyone tell me how non-standard?) but it makes my life easier. essentially, there's a string of ones and zeros:
    0001001111011 etc
    i want to parse them eight bits at a time, and combine them into one unsigned char to be later written to a string, and then to a file. later on i'm going to add three bits to the end to show how much of the packet is left at the end. in other words:
    11111111 01010101 10111110 10: 010 is 2, meaning 3 8 bit packets (aka, bytes) and 2 bits left over. the left over bits will have zeros added to pad it up to a full byte.
    11111111 01010101 10111110 10000000
    for some reason the above code doesn't work. can anyone spot problems? thanks for your time
    Last edited by ygfperson; 04-19-2002 at 08:52 PM.

  2. #2
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    Try:
    Code:
    string to_string() {
        string temp;
        unsigned char x=0;
        for (int i=0;i<bitt.size();i++) {
          if (i%8==0 && i!=0) { temp+=x; x=0; }
          if (bitt[i])
    	    x |= (unsigned char)pow(2,i%8);
        }
        temp+=x;
        return temp;
      }
    Or you could use a mask:
    Code:
    string to_string()
    {
        string temp;
        unsigned char x=0;
        unsigned char mask = 1;
        for (int i=0;i<bitt.size();i++) {
          if (i%8==0 && i!=0) { temp+=x; x=0; mask=1;}
          if (bitt[i])
    	    x |= mask;
          mask <<= 1;
        }
        temp+=x;
        return temp;
      }

  3. #3
    Just because ygfperson's Avatar
    Join Date
    Jan 2002
    Posts
    2,490
    oh, i see. thanks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Lame null append cause buffer to crash
    By cmoo in forum C Programming
    Replies: 8
    Last Post: 12-29-2008, 03:27 AM
  2. help with c program: binary to ascii program
    By bigmac(rexdale) in forum C Programming
    Replies: 26
    Last Post: 02-03-2008, 02:26 PM
  3. Wininet Binary and ASCII
    By maxorator in forum Windows Programming
    Replies: 5
    Last Post: 11-26-2005, 03:16 AM
  4. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  5. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM