Download presentation
Presentation is loading. Please wait.
1
Bit-Level Discussion of Numeric Types
Homework 2 has been extended to October 4th, 2017 Finish reading Chapter 2 of Kernigan and Ritchie
2
Review of char and int types
char type 8 bits, 1 byte Example: int type 32 bits, 4 bytes '\x5d' 93 ']' 0x6ace9718
3
Numeric Literals signed char literals signed int literals Example:
Will be treated as an r-value of type signed char signed int literals Will be treated as an r-value of type signed int '\x##' 0x########
4
Explicit Casting Casting is the act of converting an r-value from one type to another. In most cases, this results in a change in bit-length of the value. Example: In memory: Another example: Note, large small drops bits char c = '\x55'; int i = (int) c; int i = 0x7fff9876; char c = (char) i;
5
Implicit Casting Just like Explicit Casting, but doesn't use the (type) operator. Example: The value of variable c must be converted to type (int) before arithmetic can be done between it and the value of variable i. char c = 100; int i = 100; printf("%d\n", c * i);
6
Negative Numbers To describe negative numbers, we need to make use of a property of binary arithmetic. Let's do this by first defining our first negative number: -1 Negative one (-1) is the number to which adding one (+1) will give us zero (0) There is only one such number: Note, adding +1 to that number actually gives us but we can't retain the carry. XXXX XXXX
7
One's Complement So, to define negative numbers in general, we need a few steps. First, we'll define the One's Complement operator (~): For any number, take it's binary representation and flip/toggle each bit. Examples: ~ ~ ~0x 0xbeefface ~0x 0xcafebabe
8
Two's Complement Using the One's Complement (~) we can define the Two's Complement as something we're familiar with: The Negative operator (–) The Two's Complement is equivalent to the One's Complement Plus One. Example: ~ = -87 = 87 ~ a9 56 56 + 01 57 \xa9 = -87 \x57 = 87
9
Fast One's Complement in Hex
Due to the fact that hex digits are just groups of four binary digits, we can perform One's Complement on them as a grouping. To perform One's Complement this way, switch hex digits (groups of 4 bits) horizontally. f 1 e 2 d 3 c 4 b 5 a 6 9 7 8 0000 1111 0001 1110 0010 1101 0011 1100 0100 1011 0101 1010 0110 1001 0111 1000
10
Casting Revisited (with Negative Numbers)
Now that we know how to represent negative numbers, there's an important behavior to describe in casting. The left-most bit of a numeric type is the Most Significant Bit (MSB) This bit corresponds to the sign of a number (positive or negative, +/–) When casting from a smaller signed type to a larger signed type, the sign expands across all added bits. Example: (int) 1 1 Note: This still corresponds to the same negative number!
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.