1

How can I do for multiplicate a float and a byte and have this result :

float f = 0.5
byte b = (byte) 0xFF;
f * b = 0x88 ??

Thanks

Florian Mac Langlade
  • 1,863
  • 7
  • 28
  • 57

2 Answers2

2

I think the problem is that .5 * -1 evaluates to -0.5; casting that result back to byte (or whatever whole-number type you want) turns it into 0... Thus, the assumption you mention in your question seems to not be correct:

public static void main(String[] args)
{
    byte b1 = (byte) 0xFF;
    byte b2 = (byte) 0xAA;
    System.out.println(b1);
    System.out.println(b2);
    System.out.println(String.format("0x%02X ", b1));
    System.out.println(String.format("0x%02X ", b2));
    System.out.println(String.format("0x%02X ", b1 * b2));

    System.out.println();

    float f = 0.5f;
    System.out.println(f);
    float res = f * b1;
    System.out.println(res);
    System.out.println((byte)res);
    System.out.println(String.format("0x%02X ", (byte)res));
}

Thus you get this output:

-1
-86
0xFF 
0xAA 
0x56 

0.5
-0.5
0
0x00 

Also you might want to check out this question for further details on the String.format-idea.

Community
  • 1
  • 1
Christian
  • 1,589
  • 1
  • 18
  • 36
0

Decimal value of 0xFF is -1, and of 0x88 is -120. Check your code logic again :)

If f is constant instead of multiplication you can use division - if you multiply some number with 0.5 is the same as dividing it with 2.

byte f = (byte) 2; 
byte b = (byte) 0xFF;
byte resutl = (byte)(b / f); 
djm.im
  • 3,295
  • 4
  • 30
  • 45