Thread: How To: Content of Array to String

  1. #1
    Registered User
    Join Date
    Apr 2014
    Posts
    3

    Question How To: Content of Array to String

    I want to convert a decimal number to binary and store it in a string so that I can use that binary output for later computation. Here is what I did

    Code:
    
    
    Code:
    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    void main()
    {
        int num; char i=0,j; char a[11]={0,0,0,0,0,0,0,0,0,0,'\0'};
        char string[11];
        printf("\nEnter the decimal number\n"); scanf("%d",&num);
        while(num>0)
        {
            a[i]=num%2;
            i++;
            num=num/2;
        }
        printf("\nThe Binary equivalent is\n");
        for(j=9;j>=0;j--)
        {
            printf("%d",a[j]);
        }
    }
    
    


    Now as you can see that all the binary output is in a[] but how do I get it into a string so that I can use something like printf("%s",string) and get the binary output ?

  2. #2
    Registered User Alpo's Avatar
    Join Date
    Apr 2014
    Posts
    877
    You can copy it into the unused string[11] on the condition

    Code:
    if (a[j]==1)
       string[j]='1';
    else
       '0';
    then just print the character string.

    Code:
    printf("%s", string);

  3. #3
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Please post your code as plain text next time, so the forum can apply line numbers and syntax highlighting.

    It's int main(), and you should return an integer at the end. Read this link.

    Note, '\0' is a character literal with a numeric value of 0, thus, the following are equivalent:
    Code:
    char a[11] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '\0'};
    char a[11] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    char a[11] = {0};  // short hand for initialize all elements to 0
    You allow 11 characters in the array/string. That is 10 chars for binary digits, and the 11th char is for null terminator. Thus, you can only support 10-bit numbers, but ints are at least 16 bits (1 for sign, 15 for value). Thus, you need bigger arrays/strings. Also, your while loop has the potential to overrun the end of the array/string since you don't check that i is always less than the size of the string. This is a good time to point out constants. Avoid magic numbers like 11. #define a constant for the max binary string length. Here's the easy solution
    Code:
    #define MAX_BINARY_STR 64  // support up to 64-bit numbers
    // this is not meant to be a global, declare it in main
    char binary_string[MAX_BINARY_STR + 1];  // +1 for the null terminator; notice how much more descriptive the variable name is compared to 'a' or 'string'
    If you specifically want this to work for int type, and to be portable, then I would do the following
    Code:
    #include <limits.h>  // has the definition of CHAR_BIT
    #define INT_BITS (sizeof(int) * CHAR_BIT)
    #define MAX_BINARY_STR INT_BITS
    // this is not meant to be a global, declare it in main
    char binary_string[MAX_BINARY_STR + 1];  // +1 for the null terminator; notice how much more descriptive the variable name is compared to 'a' or 'string'
    I'm not sure if you really need a second array, if you are doing everything as a string. Just convert num directly to the string representation (i.e. using '0' and '1' instead of 0 and 1). Besides, that way you don't have to worry about how long the array is, since the null termination of the string will tell you where the end is.
    Code:
    while (num > 0 && i < MAX_BINARY_STR) {
        if (num % 2)
            binary_string[i++] = '1';
        else
            '0'
    }
    binary_string[i] = '\0';  // null-terminate the string
    
    // reverse the string in place if needed -- you can probably figure this out yourself -- or simply print from the end of the string to the beginning
    Last edited by anduril462; 04-16-2014 at 03:22 PM.

  4. #4
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Quote Originally Posted by Alpo View Post
    You can copy it into the unused string[11] on the condition
    Eek! No. string[11] does not exist. You always define an array by it's size, not it's max index. In C, array indexes start at 0 and go to size-1. Thus, there is only string[0]...string[10].

  5. #5
    Registered User Alpo's Avatar
    Join Date
    Apr 2014
    Posts
    877
    @Anduril- I was just naming it as he declared it, the integer j in the for loop was only going through 10 numbers, so it wouldn't go over. I didn't mean copy a string to the 11th element of the string.
    Last edited by Alpo; 04-16-2014 at 04:22 PM.

  6. #6
    Registered User
    Join Date
    Apr 2014
    Posts
    3
    Quote Originally Posted by Alpo View Post
    You can copy it into the unused string[11] on the condition

    Code:
    if (a[j]==1)
       string[j]='1';
    else
       '0';
    then just print the character string.

    Code:
    printf("%s", string);
    This solution works perfect, all I need to do is reverse the string, thank you for our time

  7. #7
    Registered User
    Join Date
    Apr 2014
    Posts
    3
    Quote Originally Posted by anduril462 View Post
    Please post your code as plain text next time, so the forum can apply line numbers and syntax highlighting.

    It's int main(), and you should return an integer at the end. Read this link.

    Note, '\0' is a character literal with a numeric value of 0, thus, the following are equivalent:
    Code:
    char a[11] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '\0'};
    char a[11] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    char a[11] = {0};  // short hand for initialize all elements to 0
    You allow 11 characters in the array/string. That is 10 chars for binary digits, and the 11th char is for null terminator. Thus, you can only support 10-bit numbers, but ints are at least 16 bits (1 for sign, 15 for value). Thus, you need bigger arrays/strings. Also, your while loop has the potential to overrun the end of the array/string since you don't check that i is always less than the size of the string. This is a good time to point out constants. Avoid magic numbers like 11. #define a constant for the max binary string length. Here's the easy solution
    Code:
    #define MAX_BINARY_STR 64  // support up to 64-bit numbers
    // this is not meant to be a global, declare it in main
    char binary_string[MAX_BINARY_STR + 1];  // +1 for the null terminator; notice how much more descriptive the variable name is compared to 'a' or 'string'
    If you specifically want this to work for int type, and to be portable, then I would do the following
    Code:
    #include <limits.h>  // has the definition of CHAR_BIT
    #define INT_BITS (sizeof(int) * CHAR_BIT)
    #define MAX_BINARY_STR INT_BITS
    // this is not meant to be a global, declare it in main
    char binary_string[MAX_BINARY_STR + 1];  // +1 for the null terminator; notice how much more descriptive the variable name is compared to 'a' or 'string'
    I'm not sure if you really need a second array, if you are doing everything as a string. Just convert num directly to the string representation (i.e. using '0' and '1' instead of 0 and 1). Besides, that way you don't have to worry about how long the array is, since the null termination of the string will tell you where the end is.
    Code:
    while (num > 0 && i < MAX_BINARY_STR) {
        if (num % 2)
            binary_string[i++] = '1';
        else
            '0'
    }
    binary_string[i] = '\0';  // null-terminate the string
    
    // reverse the string in place if needed -- you can probably figure this out yourself -- or simply print from the end of the string to the beginning
    Whao!! Your information is so much informative. Loved it. Thanks a lot
    I kept that binary string to 10 bit intentionally as I will be using this code in some embedded hardware (PIC) where I need 10 bit binary data from a decimal data which can lead to a maximum value of 1023.

    Thanks a lot. I will make sure I start my code with int main() next time.

  8. #8
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Quote Originally Posted by rishiraj View Post
    Whao!! Your information is so much informative. Loved it. Thanks a lot
    You're welcome.
    Quote Originally Posted by rishiraj View Post
    ...I will be using this code in some embedded hardware (PIC)...I will make sure I start my code with int main() next time.
    Didn't realize you were on an embedded system. They don't have the same requirements, since they don't necessarily have a host operating system that it makes sense to return a status code to (which is why main returns an int). Thus, some embedded systems specify that you use int main, some void main, some allow either, and they could even require you return a char pointer; they are also not required to use the name "main" for the function that is called first on program startup, and they even are not required to provide the full set of library functions. It all depends on the system, you would have to check the documentation to find out what is allowed or expected for your system. Still, if you're not sure, int main is probably your best bet.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Simplest way to calculate the string content?
    By pvujic in forum C++ Programming
    Replies: 3
    Last Post: 11-19-2009, 03:04 PM
  2. trouble adding content to string
    By letsgetaway in forum C++ Programming
    Replies: 9
    Last Post: 01-20-2008, 12:54 PM
  3. Replies: 4
    Last Post: 04-03-2007, 05:57 AM
  4. File content -> string?
    By 7smurfs in forum C++ Programming
    Replies: 9
    Last Post: 03-30-2005, 11:02 AM
  5. How do I delete the content of a char && string ??
    By client in forum C Programming
    Replies: 2
    Last Post: 06-01-2002, 05:09 AM