Thread: Binary to string

  1. #1

    Post Binary to string

    Hello everyone,

    I am having a bit of trouble. I am trying to read a string and convert it to binary. I finished the code, and it works, but I can't figure out how to convert binary back to string.

    Here is what I have so far:

    Code:
    #include <stdlib.h>
    #include <string.h>
    
    int power(int, int);
    char* stob(char *);	// string to binary
    
    int main() {
    	char str[1024];
    
    	printf("Enter some text: ");
    	scanf("%s", str);
    
    	printf("Binary value: %s\n", stob(str));
    
    	return 0;
    }
    
    int power(int base, int exponent) {
    	int p;
    
    	for (p = 1; exponent > 0; --exponent) 
    		p = p * base;
    
    	return p;
    }
    
    char* stob(char *str) {
    	int i, j, len;
    	static char temp[8192];
    	char *buffer = &temp[0];
    
    	buffer[0] = '\0';
    	len = (strlen(str) > 1024) ? 1024 : strlen(str);
    
    	for (i = 0; i < len; i++) {
    		for (j = 7; j >= 0; j--) {
    			if (str[i] >= power(2, j)) {
    				strcat(buffer, "1");
    				str[i] -= power(2, j);
    			}else {
    				strcat(buffer, "0");
    			}
    		}
    		strcat(buffer, " ");
    	}
    
    	return buffer;
    }
    I just don't know how I'd write to convert that binary value back to a string. I have some ideas, but they don't seem to be right. Can anyone assist me in this?

    Also, sry I didn't feel like using pow() from math.h so I wrote my own, doh.


    - Stack Overflow
    Last edited by Stack Overflow; 04-22-2004 at 05:09 PM.
    Segmentation Fault: I am an error in which a running program attempts to access memory not allocated to it and core dumps with a segmentation violation error. This is often caused by improper usage of pointers, attempts to access a non-existent or read-only physical memory address, re-use of memory if freed within the same scope, de-referencing a null pointer, or (in C) inadvertently using a non-pointer variable as a pointer.

  2. #2
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    Use strtol()
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  3. #3
    Registered User linuxdude's Avatar
    Join Date
    Mar 2003
    Location
    Louisiana
    Posts
    926
    char *bin = "1100";
    int number;

    number = strtol(bin, (bin + sizeof(bin), 2);

  4. #4
    Oh, it didnt compile.

    I also tried making it like:

    number = strtol(bin, (bin + sizeof(bin)), 2);

    then I got an error: 'strtol' : cannot convert parameter 2 from 'char *' to 'char ** '

    Dunno, it might just be me.

    - Stack Overflow
    Segmentation Fault: I am an error in which a running program attempts to access memory not allocated to it and core dumps with a segmentation violation error. This is often caused by improper usage of pointers, attempts to access a non-existent or read-only physical memory address, re-use of memory if freed within the same scope, de-referencing a null pointer, or (in C) inadvertently using a non-pointer variable as a pointer.

  5. #5
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    >number = strtol(bin, (bin + sizeof(bin)), 2);

    That second parameter is a pointer to where it stopped translating. You either have to declare an endptr, or make it NULL if you don't need to know where it stopped.

    number = strtol( bin, NULL, 2 );

  6. #6
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    Code:
    #include <limits.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    /* You aren't supposed to understand this */
    int btod ( const char *b )
    {
      return *b ? btod ( b + 1 ) + ( *b - '0' << strlen ( b ) - 1 ) : 0;
    }
    
    /* Nor are you supposed to take it seriously */
    long double dtob ( int d )
    {
      return d ? dtob ( d >> 1 ) * 10 + ( d & 1 ) : 0;
    }
    
    char *stob ( char *str )
    {
      char buf[CHAR_BIT + 1];
      char *bin = malloc ( strlen ( str ) * ( CHAR_BIT - 1 ) + 1 );
    
      bin[0] = '\0';
      while ( *str != '\0' ) {
        sprintf ( buf, "%.0Lf", dtob ( *str++ ) );
        strcat ( bin, buf );
      }
    
      return bin;
    }
    
    char *btos ( char *bin )
    {
      char buf[CHAR_BIT - 1 + 1];
      char *str = malloc ( strlen ( bin ) / ( CHAR_BIT - 1 ) + 1 );
      int i = 0;
    
      while ( *bin != '\0' ) {
        buf[0] = '\0';
        strncat ( buf, bin, CHAR_BIT - 1 );
        str[i++] = (char)btod ( buf );
        bin += CHAR_BIT - 1;
      }
      str[i] = '\0';
    
      return str;
    }
    
    int main ( void )
    {
      char *bin = stob ( "abc" );
      char *str;
    
      puts ( bin );
      str = btos ( bin );
      puts ( str );
      free ( str );
      free ( bin );
    
      return 0;
    }
    My best code is written with the delete key.

  7. #7

    Post

    Ah ,

    Thanks alot Prelude, and everyone!

    - Stack Overflow
    Segmentation Fault: I am an error in which a running program attempts to access memory not allocated to it and core dumps with a segmentation violation error. This is often caused by improper usage of pointers, attempts to access a non-existent or read-only physical memory address, re-use of memory if freed within the same scope, de-referencing a null pointer, or (in C) inadvertently using a non-pointer variable as a pointer.

  8. #8
    Yes, my avatar is stolen anonytmouse's Avatar
    Join Date
    Dec 2002
    Posts
    2,544
    Given your user name, it is somewhat appropriate that your code includes:
    Code:
    	scanf("%s", str);

  9. #9
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    Quote Originally Posted by anonytmouse
    Given your user name, it is somewhat appropriate that your code includes:
    Code:
    	scanf("%s", str);
    It is rather ironic, isn't it? But I see a steady progression in most C programmers:
    Code:
    /* Newbie */
    scanf ( "%s", string );
    becomes
    Code:
    /* Warned about buffer overflow */
    scanf ( "%1023s", string );
    becomes
    Code:
    /* Really neat trick! */
    sprintf ( fmt, "%%%ds", sizeof string - 1 );
    scanf ( fmt, string );
    becomes
    Code:
    /* Never use scanf */
    fgets ( string, sizeof string, stdin );
    becomes
    Code:
    /* Too lazy to do it right */
    scanf ( "%s", string );
    becomes
    Code:
    /* Got burned with scanf */
    fgets ( string, sizeof string, stdin );
    Some even go so far as to say that fgetc is the only "right" way to do it because it gives you the most control, but not many actually practice what they preach.
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. OOP Question DB Access Wrapper Classes
    By digioz in forum C# Programming
    Replies: 2
    Last Post: 09-07-2008, 04:30 PM
  2. String issues
    By The_professor in forum C++ Programming
    Replies: 7
    Last Post: 06-12-2007, 09:11 AM
  3. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 05:45 PM
  4. Compile Error that i dont understand
    By bobthebullet990 in forum C++ Programming
    Replies: 5
    Last Post: 05-05-2006, 09:19 AM
  5. 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