-1

probably there is a smart way to do that , but anyway i get error on this :

-(int*)decimalBinary:(int)decimal
{
    int i=0;
    int *bin;
    while (decimal!=0)
    {
        bin[i]=decimal%2;
        decimal=decimal/2;
        i++;
    }

    return bin;

}

on the modulo line . why ? And whats the better way to get it to array ?

12
  • Print binary batter use bitwise operators: read: Decimal to Binary: Size independent Commented Sep 18, 2013 at 16:45
  • 5
    I'm not familiar with objective c, but shouldn't a pointer be initialised before use? In plain C, you'd have to initialise the pointer with either passing an array to it, or (m|c|?)alloc() functions... Commented Sep 18, 2013 at 16:46
  • Change int *bin to int bin[sizeof(int) + 1. Set a point to end of buf and fill backwards, decrementing the pointer each step. Commented Sep 18, 2013 at 16:49
  • i dont think it has to do with objC, its just a C pointer . but i did tried to initialize it and still got error. if i set :b[1] instead of zero , its not crashing . Commented Sep 18, 2013 at 16:49
  • Look this answer stackoverflow.com/questions/11797460/… Commented Sep 18, 2013 at 16:50

2 Answers 2

0

Declaring

int *bin;

sets aside space for a pointer but doesn't make it point to an object. It is crucial to initialize bin before using it.
To solve your problem you can declare an array bin[4] in caller function (int main) and then pass *bin to your calling function.

Sign up to request clarification or add additional context in comments.

Comments

0

The following code is adapted from This answer on how to print an integer in binary format. Storing "binary digits" into an int array is added into the code below:

#include <stdio.h>      /* printf */
#include <stdlib.h>     /* strtol */

const char *byte_to_binary(long x);

int main(void)
{
    long lVal;
    int i, len, array[18];
    char buf[18];

    {   /* binary string to int */
        char *tmp;
        char *b = "11010111001010110";

        lVal=strtol(b, &tmp, 2); //convert string in "base 2" format to long int
        printf("%d\n", lVal);
    }
    {
        printf("%s", byte_to_binary(lVal));
        /* byte to binary string */
        sprintf(buf,"%s", byte_to_binary(lVal));
    }
    len = strlen(buf);
    for(i=0;i<len;i++)
    {   //store binary digits into an array.
        array[i] = (buf[i]-'0');    
    }
    getchar();
    return 0;
}

const char *byte_to_binary(long x)
{
    static char b[17]; //16 bits plus '\0'
    b[0] = '\0';
    char *p = b;  

    int z;
    for (z = 65536; z > 0; z >>= 1)    //2^16
    {
        *p++ = (x & z) ? '1' : '0';
    }
    return b;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.