Win a copy of Kotlin in Action this week in the Kotlin forum!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Conversion issue

Vishy Karl
Ranch Hand
Posts: 116
Hi all,
I am having a doubt in the questions involving hexadecimal numbers.
i had this question in a mock exam

int ab = 0xFFFFFFFA;
int invertedA = ~ab;

Now how am i supposed to find value of ab which is -6,i mean am is supposed to write
A * 16^0 + F * 16^1 + F * 16^2 and so on ???
i don't think this is the proper way,is there no easier way ? how will i get -6 as the answer.
plz. solve my doubt,

Steve Lovelace
Ranch Hand
Posts: 125
First, I believe the answer is 5, not -6.
To see how to do the inversion easily, picture what this number looks like in binary. It is:
11111111 11111111 11111111 11111010
Inverting means 1 becomes 0 and vice versa:
00000000 00000000 00000000 00000101
or 101 for short, which is to say 5.

Jessica Sant
Sheriff
Posts: 4313
Originally posted by Steve Lovelace:

11111111 11111111 11111111 11111010
Inverting means 1 becomes 0 and vice versa:
00000000 00000000 00000000 00000101
or 101 for short, which is to say 5.

Don't forget!!! Two's complement means you need to invert the number and then add 1!
So -->

11111111 11111111 11111111 11111010
00000000 00000000 00000000 00000101
+ 1
-----------------------------------
00000000 00000000 00000000 00000110
== 6
So that means it really is -6
But I agree -- the easiest way I've found to convert hex digits is first to convert it to binary then two's complement it (if its negative) and then figure out the decimal representation.

Dimple Kaushik
Ranch Hand
Posts: 49
ab=0xFFFFFFFA
in hexadecimal A=10, B=11, C=12, D=13, E=14, F=15
in binary 10,11,12,13,14,15 are 1010, 1011, 1100, 1101, 1110, 1111 resp
so ab = 1111 1111 1111 1111 1111 1111 1111 1010
~ab = 0000 0000 0000 0000 0000 0000 0000 0101 + 1 = 110 = -6

Can anybody tell me how to convert these?
byte a = (byte)127;
byte b = (byte)128;
byte c = (byte)255;
byte d = (byte)256;
//......
System.out.print(a + " " + b + " " + c + " " + d);
Ans: a = 127, b = -128, c = -1, d = 0
Thanks.
[ November 19, 2003: Message edited by: dimple kaushik ]

Vishy Karl
Ranch Hand
Posts: 116
Thanks all
Jessica the number given ab is itself -6 according to 2's complement .
then after the operation
int invertedA = ~ab;
it comes to sign change and answer as 5