首页 > 代码库 > Chap 2 Representing and Manipulating Information (CS:APP)
Chap 2 Representing and Manipulating Information (CS:APP)
--------------------------------------------------------------------------------------------------
Author: YuManZI
2014/06/23 1.1-3.5
2014/06/24 3.6-3.8
2014/06/27 4.1
2014/06/28 4.2-4.5
--------------------------------------------------------------------------------------------------
1. Information Storage
1.1 Virtual Memory: a machine-level program views memory as a very large array of bytes.
1.2 Data Sizes (bytes)
32 bit: char 1; short [int] 2; int 4; long [int] 4; long long [int] 8; char *(any pointer) 4; float 4; double 8;
64 bit: char 1; short [int] 2; int 4; long [int]8; long long [int] 8; char *(any pointer)8; float 4; double 8;
Contents within square brackets [] are optional. The main difference between 32 bit and 64 bit machines are following two points: a) different sizes of data type long; b) different sizes of pointers.
1.3 Byte Ordering: big endian & little endian. (Takinh 0x01234567 as example.)
Big endian, the most significant byte comes first(lower address), bytes from low address to high address are 01 23 45 67, respectively;
Little endian, the least significant byte comes first(lower address), bytes from low address to high address are 67 45 23 01, respectively.
1.4 Shift Operations in C
Left shift << k: dropping off the k most significant bits and filling the right end with k zero;
Logical right shift >>k: dropping off the k least significant bits and filling the lest end with k zero;
Arithmetic right shift >>k: dropping off the k least significant bits and filling the lest end with k themost significant bit.
Arithmetic right shift uses the most significant bit as filling unit, because of the two‘s complement representation of negative integers. In some languages(e.g. java), the number of shifting bits can never be more than bit sizes of data types.
2. Integral Data Types
2.1 Unsigned Encodings (w bits, x=[x_(w-1), x_(w-2),...,x_0])
B2U(x)=sigma{i=[0,w-1]}(x_i*2^i)
B2U means Bits to Unsigned
It can represent integers between [0..2^w-1]
2.2 Two‘s-Complement Encodings (same setting as 2.1)
B2T(x)=-x_(w-1)*2^(w-1) + sigma{i=[0,w-2]}(x_i*2^i)
B2T means Bits to Two‘s
It‘s a signed encoding, can represent integers between [-2^(w-1), 2^(w-1)-1], the difference between it and Unsigned encoddings are the weight of the significant bit, i.e. positive for unsigned and negative for two‘s-complement.
2.3 Conversions
Signed<-->Unsigned with identical size: the key is to keep bit representation stable;
Large size-> Small size with same type of signed or unsigned: truncate directly;
<
Chap 2 Representing and Manipulating Information (CS:APP)