CSCI 235 — Sections 2.1 to 2.3
CMU 15-215 Video to view
Stuff to do
- Bases of Java literals
- decimal
235
- octal
0235710
- hexadecimal
0x235eA
- binary
0b0110001010111 — not in C (but in GCC)
- Examples to do
- decimal ↔ binary and hexadecimal
- binary ↔ octal ↔ hexadecimal
0b1101001101
0666
0xE1E10
- Integer types of Java — C also has
unsigned types
byte, 8 bits — in C99, int8_t
short, 16 bits — in C99, int16_t
int, 32 bits — in C99, int32_t
long, 64 bits — in C99, int64_t
char, 16 bits — in C99, uint16_t
- Questions to answer
- Given the range of the signed Java types, what should be the range of C’s corresponding
unsigned data types?
- What is special about 65535?
- Bitwise operators of Java
~,
&, |, and ^
- Examples to do
~235
235 & 100
235 | 100
235 ^ 100
- Questions to answer, for positive numbers.
- Is
x | y > x ?
- Is
x & y > x ?
- Is
x ^ y > x ?
- Representation of negative numbers — two’s complement only
- Negative weight to the most significant bit
- You must know the number of bits
- Examples to do in 10-bit two’s complement
- Shift operators of Java —
<<,
>>, >>> (not in C)
- Arithmetic vs logical right shift
- You must know the number of bits
- Examples to do in 12-bit. Assume are all signed.
235 >> 2
-235 >> 2
235 << 2
- Widening and narrowing casts
- Java defines widening and narrowing casts
- In C,
unsigned makes this difficult; however,
narrowing is fine, if input within the output range
- References for C
- Practice problems 2.25 and 2.26 (p. 83)
- Overflow — signed and unsigned arithmetic
- If it makes no sense to the 5th grader, it is wrong!
- Examples to do in 10-bit signed
235 + 888
235 + 400
-235 + -100
- Examples to do in 10-bit unsigned
- Optimizing multiplication and division by constants
X<<n multiplies by 2n
— if result in range
X>>n divides by 2n
— if result in range, but
rounding is downward not toward zero
Z = X*1000 ; is probably slower than
T = X<<3 ;
Z = X<<10 - T - T - T ;
- Practice Problem 2.40 (p. 40)