Hi,
I'm reading a binary file, in which I know that at a certain
index I'll be reading integer numbers. Everything works
fine until a certain point where i encouter 0xE8, and I'm
returned -24 instead of 232.
The function I use is the following:
public static int getIntValue(short b)
{
return (int)b;
}
How come it doesn't work for 0xE8 ??
Thanks.
Filip Larsen - 26 Aug 2006 09:46 GMT
> I'm reading a binary file, in which I know that at a certain
> index I'll be reading integer numbers. Everything works
> fine until a certain point where i encouter 0xE8, and I'm
> returned -24 instead of 232.
In Java the types byte, short, int and long are all signed types, which
means that when a smaller type gets converted into a bigger type (short
to int for instance) the sign bit of the small type gets extended into
the larger type. This can happen when you make an explicite cast or when
the compiler implicitely promotes values to int or long before
evaluation in expressions. If your numbers really are unsigned you must
mask off the extended bits to "keep" them unsigned.
> The function I use is the following:
> public static int getIntValue(short b)
> {
> return (int)b;
> }
You could do
public static int getIntValue(short b) {
return ((int)b)&0xFFFF;
}
Best regards,

Signature
Filip Larsen
Chris Uppal - 26 Aug 2006 10:13 GMT
> public static int getIntValue(short b) {
> return ((int)b)&0xFFFF;
> }
Nitpick: you don't need the cast, which might cause confusion in beginners (if
you care) -- the expression is of type int anyway if you express it as
(b & 0xFFFF)
-- chris
Babu Kalakrishnan - 26 Aug 2006 12:35 GMT
> Hi,
> I'm reading a binary file, in which I know that at a certain
[quoted text clipped - 8 lines]
>
> How come it doesn't work for 0xE8 ??
I don't think it is the above portion of the code which is giving you
trouble. Calling your function with (short)0xE8 as the argument will
return 232 as the value and not -24
I suspect the 0xE8 begins its life as a byte somewhere in your code.
(Reading it as a byte from the file ?) - For instance :
byte b = (byte)0xE8;
int n= getIntValue(b); // this will cause n to be -24 because byte is
an 8 bit signed entity
Incidentally, your getIntValue() function is largely unnecessary - As
Chris pointed out, a promotion to "int" is automatic for all
expressions involving integer types smaller than an int (short , char
or byte) - so a simple assignmet will suffice : i.e. the second
statement above does nothing more than
int n = b;
BK