Bit Representation: Difference between revisions

From Dev Wiki
Jump to navigation Jump to search
(Create page)
 
(Create data type size section)
Line 35: Line 35:
<code>-(0 + 2 + 0) = -2</code><br>
<code>-(0 + 2 + 0) = -2</code><br>
Our resulting value is <code>-2</code>
Our resulting value is <code>-2</code>
== Data Type Sizes ==
The following table describes how many bytes are needed to represent each data type.<br>
Recall that 1 byte is 8 bits.
{| class="wikitable"
|-
!
! Standard 32-bit
! Standard 64-bit
! x86-64
|-
! Char
| 1
| 1
| 1
|-
! Short
| 2
| 2
| 2
|-
! Int
| 4
| 4
| 4
|-
! Long
| 4
| 8
| 8
|-
! Float
| 8
| 8
| 8
|-
! Double
| 8
| 8
| 8
|-
! Long Double
| -
| -
| 10 / 16
|-
! Pointer
| 4
| 8
| 8
|}

Revision as of 02:27, 4 February 2020

Two's Compliment

Also known as "signed integer" representation.

At the bit level, everything is computed and stored the same as unsigned.
However, when representing the number to the user, it's handled differently.

Effectively:

  • Check the largest (leftmost) bit.
    • If it's 0, then compute normally, the same as unsigned.
    • If it's 1, the value is negative, so proceed to the next steps.
  • Drop off the largest (leftmost) bit, as we know the value is negative.
  • Invert remaining bits.
  • Add 1 to these inverted bit.
  • Read in new value as your number, as a negative.

Two's Compliment Examples

Positive Example: 0110

We read this in normally, so we would have:
0 + 4 + 2 + 0 = 6
Our resulting value is 7.

Negative Example: 1110

Our leftmost bit is 1, so we know it's negative.
First, we drop this leftmost bit, giving us 110.
Next, we invert our bits, giving 001.
Now we add 1 to our inverted value:

 001
+  1
 ---
 010

Our final binary value is 010. We can now read this as a negative number, giving:
-(0 + 2 + 0) = -2
Our resulting value is -2

Data Type Sizes

The following table describes how many bytes are needed to represent each data type.
Recall that 1 byte is 8 bits.

Standard 32-bit Standard 64-bit x86-64
Char 1 1 1
Short 2 2 2
Int 4 4 4
Long 4 8 8
Float 8 8 8
Double 8 8 8
Long Double - - 10 / 16
Pointer 4 8 8