Thread: Binary to string

Threaded View

Previous Post Previous Post   Next Post Next Post
  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.

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