int to double type casting

govvj

Govind Vijay

Posted on December 15, 2021

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.

💖 💪 🙅 🚩
govvj
Govind Vijay

Posted on December 15, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related