Storing negative numbers as binary

As a programmer and computer enthusiast it is very helpful to know how numbers are stored in memory, also known as RAM. Well everybody knows that information is stored as a stream of binary digits known as Bits, that are made up of 1s and 0s. 8 of those bits build a Byte. One number type is called a Whole number, or Integer in computer terms. Those can be negative and positive, or in other words signed and unsigned respectively. Now comes the question of how to store those numbers effectively? This is what I will show you in this blog.

As an example we will take the number 5, which is represented in binary as: 00000101. This part is easy if you know how decimal and dual number systems work, and I know most geeks know. ;-) Now to change this 5 into a -5 there are two steps we need to take and those steps are called One’s Complement and Two’s complement.

With one’s complement we simply need to swap the bits so we get 11111010. This is the first step, but this isn’t efficient enough, so we need to do the two’s complement next, in which we simply add 1 or 00000001 to it, which will give us 11111011 which will be a -5 in a 8 bit storage.

I hope this was helpful for you, and please comment if you want to add something to it.

Happy Hacking, and stay crispy in milk xD

Advertisement

~ by austrogeek on August 29, 2010.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.