2.2 Integer representation

2.2.2 Unsigned Encoding

Both C and C++ support signed(the default) and unsigned numbers, and Java support only signed numbers.

we denote to be the entire bit vector, and devote individual bits as within the vector.

The function , for “binary to unsigned”,length w:image

where represents the ith value int bit vector, 0 or 1.

                                     image

      We write   and  is a bijection – it associates an unique value to each bit vector of length ,conversely integer between 0 and has an unique binary representation as a bit vector of length  .

2.2.3 Two’s-Complement Encoding

Two’s-Complement form is used for signed  numbers in the computer representation.

We express the function ,for “binary to two’s complement”,length :

image

image We write , and is also bijection.

Programs are portable across a broad range of machines and compilers. The file <limits.h>  in C library defines a varity of constants delimiting the ranges of different integer  data types for the particular machine the compiler is running. For example it defines the constants INT_MAX, INT_MIN, UINT_MAX describing the ranges of signed and unsigned integers. For a two’s-complement machine int which the int data type has w bits, these constants correspond to the values of , , .

The ISO standard introduces another class of integer data types in the file <stdint.h> .This file defines a set of data types with the declaration of the forms intN_t and uintN_t, specifying N-bits signed and unsigned integers, for the different value. For example, int64_t i = 5; Along with these data types are a set of macros defining maximum and minimum values for each value of N. These have names of the form INTN_MAX, INTN_MIN, UINTN_MAX.

In two’s-comlement, for a nonnegetive x, we compute a w-bit reprentation –x as .

2.2.4 Covensions Between Signed and Unsigned

In casting between signed and unsigned, the underlying bit representation stays the same.

Since and are bijection, we can define to be , and to be .

Let , We compute the different :

,    as , and

Thus, , when ,, and when x<0,

image

The following figure illustrates  this process when w = 4.

image 

image

The blue line means the situation when x>=0, while the gray curve indicates the situation x<0.

                             image

image

原文地址:https://www.cnblogs.com/baiweiguo/p/2861333.html