0

why assignment of binary to float or double is causing an error.

here is my first code which works well-

float myFloat1 = 0b111; //prints 7.0
double myDouble1 = 0b111; //prints 7.0

here is the second code

float myFloat2 = 0b111f; //compiler complains ';' expected
double myDouble2 = 0b111d; //compiler complains ';' expected

In the second code compilers complains that ';' expected, what's going on in second code snippet? Any help will be greatly appreciated.

Hello World
  • 944
  • 2
  • 15
  • 39

2 Answers2

2

The 0bxxx specifies an integer, but this can't be modified with d or f to convert it to a floating-point value. But you can use a cast:

float myFloat2 = (float) 0b111;
double myDouble2 = (double) 0b111;
mob
  • 117,087
  • 18
  • 149
  • 283
  • :How about long type. long myLong1=0b101010101010101010101010101010L; long myLong1=0b101010101010101010101010101010; print 715827882 in both above lines. – Hello World May 05 '14 at 16:11
  • Then you answered your own questioh – mob May 05 '14 at 16:13
  • :No, I mean if long is printing it in both ways then why not float and double? – Hello World May 05 '14 at 16:17
  • Because [that's what the spec says](http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.1). A valid integer literal can have the suffix `l` or `L`. A valid floating-point literal can have the suffix `f`, `d`, `F`, or `D`. `0b111` is an integer literal. – mob May 05 '14 at 16:25
0

Hi if you just use float x=7;

then it assumes 7 is integer and trying to assign to float so compile time error comes

so to make it work we have to do

float x=7f;

but if the number is starting with 0 in java it assumes it as Octal number

and for octal number you should not append anything like f or d. so float x=0b111; is fine instead of float x =0111f;

also remember float x=0181; is invalid because octal number should have digits only from 0 to 7 and its having one of the digit 8.

Karibasappa G C
  • 2,686
  • 1
  • 18
  • 27