DEV Community

Govind Vijay
Govind Vijay

Posted on

int to double type casting

Hi all,
Say you have a 4 byte integer and now you want to convert it to double. You might say that's easy, just add couple of zeros to the front. It's not that simple. Its only work for positive integers.

For simplicity lets assume you have 4 bit integer and you want to convert it to 8 bit.

Let a = -3 = (1101) -> 2's complement

1101 -> 0010 (1s complement) + 1 -> 0011 -> 3
Enter fullscreen mode Exit fullscreen mode

Now if you just add zeros then it will become
a = (00001101) = 13
So instead you take the most significant digit (i.e. 4th bit) and paste it to the new bits.
copy msb bits

a = (11111101) = (00000010 + 1) = (00000011) = 3 -> -3

Note: when a = 13 we didn't do 2's complement because right most bit was zero.

Top comments (0)