18

something I thought was simple ends up not so much.

I need to convert a long number to binary.

For example:

String b =  Integer.toBinaryString(1028);

the output is 10000000100

but when I use Integer.toBinaryString(2199023255552); it does not work. Of course the number is too big for this function and I can't find one that does convert from long.

Any suggestions?

Thank you.

Steve
  • 1,028
  • 7
  • 25
  • 42

1 Answers1

53

Add an L to indicate its a long<1> and use the Long class<2>:

Long.toBinaryString(2199023255552L);

<1> Constants in java are considered ints unless you specify otherwise.

<2> Integer.toBinaryString() receives an int as parameter, not long.

MByD
  • 135,866
  • 28
  • 264
  • 277
  • Thank you very much. Sorry, I first did not see the L. Kind of strange but ok.... – Steve Aug 07 '11 at 01:53
  • I am curious, I always have to use the L at the end? I was looking at all the samples I found online and none have that. – Steve Aug 07 '11 at 02:28
  • When you want to specify a `long`, then yes. – MByD Aug 07 '11 at 02:30
  • 1
    @Eng.Fouad - Your comment seemed familiar to me :) http://stackoverflow.com/questions/6834037/initialize-a-long-in-java/6834049#6834049 – MByD Aug 07 '11 at 02:48
  • @MByD lol what a Coincidence. I remember I said that for someone but never expected it's for same person and similar answer. wow! – Eng.Fouad Aug 07 '11 at 03:02