Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 315325
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T08:16:53+00:00 2026-05-12T08:16:53+00:00

The question is in the title I guess. This is the temporary solution I

  • 0

The question is in the title I guess.

This is the temporary solution I came up with but I was wondering:

  • If there are disadvantages to representing binary as char*. Is there a better way (considering i would want the ability of bit-shifting etc…)
  • If there is obvious non-idiomatic C (or other errors) in the code below.

All suggestions welcome…

#include <math.h>
#include <stdio.h>
#include <stdlib.h>

/* compile with 
    gcc -lm -std=c99 
*/

void binary_repr(unsigned long input) {
    int needed_digits = (int) (floor(log2(input)) + 1);
    char *ptr_binarray = malloc((needed_digits + 1) * sizeof (char));
    int idx = (needed_digits);

    if (ptr_binarray == NULL) {
            printf("Unable to allocate memory.");
        exit(1);
    } 
    else {
        do {
            idx--;
            if (input % 2 == 0) { 
                ptr_binarray[idx] = '0'; 
            } 
            else { 
                ptr_binarray[idx] = '1'; 
            }
            input = input / 2;

        } while (input > 0);

        ptr_binarray[needed_digits] = '\0';
        printf("%s\n", ptr_binarray);
        free(ptr_binarray);
        ptr_binarray = NULL;
    }
}

int main()
{
    binary_repr(8);
    binary_repr(14);
    binary_repr(4097);
    return 0;
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-12T08:16:53+00:00Added an answer on May 12, 2026 at 8:16 am

    Looks approximately idiomatic to me, except that I’d write the loop something like:

    char *writeptr = ptr_binarray + needed_digits;
    *writeptr = 0;
    do {
        --writeptr;
        *writeptr = (input % 2) + '0';
        input /= 2;
    } while (input > 0);
    

    No need for an integer index.

    For this particular case, I wouldn’t bother with malloc since you free in the same function. Just allocate a big enough char array on the stack:

    char binarray[sizeof(unsigned long)*CHAR_BIT + 1];
    

    Or make use of C99’s variable length arrays:

    char binarray[needed_digits + 1];
    

    Also, if you’re only using gcc, then rather than taking a logarithm you could consider using __builtin_clz to calculate needed_digits. That’s not about idiomatic C, though, since it’s the gcc dialect. But even without it, you don’t need floating point math to figure out how many digits are needed:

    http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious

    Just noticed a probable error in that line, too – your do/while loop neatly handles the case where input is 0, but the first line doesn’t since you can’t take the log of 0.

    Is there a better way (considering i would want the ability of bit-shifting etc…)

    Not sure what you mean here. If you want to do operations like bit-shifting on a value, then don’t convert it to a string like this. Keep it as a long int, and do your bit-shifting there.

    Other minor things, since you’re asking for general opinions. None of these are things I’d really criticise as long as you have a reason you’ve done them:

    • Remove pointless parens around (needed_digits), it’s just noise.
    • Error message should probably go to stderr rather than stdout.
    • I would always check the return value from malloc (or any other function that returns an error value) immediately, rather than have a line of code in between. So move the int idx = needed_digits line down to just before the ‘do .. while’ loop (since you’re using std=c99. If it was c89, then you could still do that except that I’m going to recommend…).
    • I wouldn’t put an “else” after a conditional exit or return. But other people would do as you have, and the argument can probably get tribal.
    • Personally I wouldn’t multiply by sizeof(char) in malloc, since the size of the buffer allocated by malloc is measured in chars by definition. But others put it there so that every malloc consistently always has a sizeof, so again I can’t claim my way is idiomatic. It’s just better 😉
    • Clearing pointers after free is arguably worthwhile when they’re in a structure, but not so much for automatics.

    For each of the last three things, good C programming practice would not necessarily be to do as I do, but to agree a coding style with your colleagues / collaborators. The coding standard is allowed to be “do as you prefer”, just so long as you agree not to argue, and not to “tidy up” each other’s code.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 244k
  • Answers 244k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Have a look at these Introduction to the Singleton Pattern… May 13, 2026 at 8:01 am
  • Editorial Team
    Editorial Team added an answer Your working directory is C:\Program Files (x86)\Java\jdk1.6.0_17\bin. You are not… May 13, 2026 at 8:01 am
  • Editorial Team
    Editorial Team added an answer To use a MapView your Activity must extend MapActivity. For… May 13, 2026 at 8:01 am

Related Questions

The question is in the title, why : return double.IsNaN(0.6d) && double.IsNaN(x); Instead of
I use contructor injection in my solution, but this one class has a property
This question is related to (but perhaps not quite the same as): Does Django
I admit it is not the best title, but I don't know how to

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.