int to double type casting
Govind Vijay
Posted on December 15, 2021
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
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.
a = (11111101) = (00000010 + 1) = (00000011) = 3 -> -3
Note: when a = 13 we didn't do 2's complement because right most bit was zero.
💖 💪 🙅 🚩
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.