jirick
jirick

Reputation: 71

C conversion of signed int as binary to long

I have a function which converts an integer to its binary representation and its stored in a long variable. My problem is that my function converts only positive integers so I need to implement a new function which will be slightly changed to do just that. I still need to store the bin. rep. in a long variable because that depends on the other features. Is there a way?

My function which successfully converts only positive integers:

long convertToBin(int decn)
{
  long binn = 0;
  long rem;
  long a = 1;
  while(decn != 0)
  {
    rem = decn % 2;
    binn = binn + rem * a;
    a = a * 10;
    decn = decn / 2;
  }
return binn;
}

I've tried it like this, but there is something wrong - doesn't work...

long negConvertToBin(int decn)
{
  long binn = 0;
  decn = abs(decn);
  decn = decn - 1;
  decn = ~decn;
  long rem;
  long a = 1;
  while(decn != 0)
  {
      rem = decn % 2;
      binn = binn + rem * a;
      a = a * 10;
      decn = decn / 2;
  }

return binn;
}

Upvotes: 1

Views: 527

Answers (2)

chux
chux

Reputation: 153557

Is there a way?

Consider code re-use since you have a working convertToBin() for positive values.

long NegAndPosConvertToBin(int decn) {
  if (decn < 0) return -convertToBin(-decn);
  return convertToBin(decn);
}

If OP still wants a stand-alone long negConvertToBin(int decn), then

long negConvertToBin(int decn) {
  decn = -decn;

  // same body as convertToBin() without the return

  return -binn;
}

As well commented by @Some programmer dude, OP's approach has limited useful int range as overflow occur with large values.


For a textual conversion for all int to various bases including 2, see char* itostr(char *dest, size_t size, int a, int base)

Upvotes: 1

user9742369
user9742369

Reputation:

i can't comment but sprintf function do works for you :

#include <stdio.h>

int main ( void )
{
    char temp[128] ;
    int num = -1  ;
    sprintf  ( temp , "%x" , num );
    puts ( temp ) ;
    return 0 ;
}

Upvotes: 1

Related Questions