LaTex+MarkDown+Pandoc組合套件寫博客的處女做,試試效果。各自的分工爲:Latex下編輯公式,在Sublime Text 2下使用Markdown排版,最後用Pandoc導出。app
本文主要講解 Binary , Unsigned , Signed 三種數據中任意二者之間的轉換。下面是文中的一些約定寫法。函數
直接用展轉相除法便可。spa
正數直接裝換,而後左邊添加0
; 負數先將其絕對值裝換成二進制數,再對低w-1
位取反,最高位添加1
,用公式表示即爲: 下面以三位的三進制數來講明有符數的補碼錶示code
\begin{equation} B2U_w\left( \overrightarrow{x} \right) \doteq \sum_{i=0}^{w-1} x_i 2^i \label{B2U} \end{equation}blog
\begin{equation}B2T_w\left( \overrightarrow{x} \right) \doteq -x_{w-1} 2^{w-1} + \sum_{i=0}^{w-2} x_i 2^i \label{B2T} \end{equation}ip
函數 T2Uw(x) 定義爲 T2Uw(x) = T2Bw(B2Uw(x)) 。這個函數輸入的是一個 -2(w-1) ~ 2(w-1)-1 之間的數,而輸出的無符數也即爲該有符數的補碼錶示。
對於位模式 下的有符二進制數 $\overrightarrow{x}$ ,對比式($\ref{B2U}$) 和式($\ref{B2T}$) , 計算二者之差,咱們就能夠獲得:$ B2U_w\left( \overrightarrow{x} \right) - B2T_w\left( \overrightarrow{x} \right) = x_{w-1} \left( 2^{w-1} - \left( -2^{w-1} \right) \right) = x_{w-1} 2^w $ 。這樣就獲得了:$B2U_w\left( \overrightarrow{x} \right) = x_{w-1} 2^w + B2T_w\left( \overrightarrow{x} \right)$。若令 $\overrightarrow{x} = T2B_w \left( x \right) $ ,則其反函數爲 $ x = B2T_w \left( \overrightarrow{x} \right) $。 由前面三式以及T → B → U變換的傳遞性,可得:get
\begin{equation} B2U_w\left( T2B_w \left( x \right) \right) = T2U_w \left( x \right) = x_{w-1} 2^w + x \label{T2U} \end{equation}
這個關係對於理解「有符數變換獲得的無符數也即補碼」頗有用。 博客
$$ T2U_w \left( x \right)=\left\{
\begin{aligned}
& x+2^w, & x<0,x_{w-1}=1 \\
& x, & x \geq 0,x_{w-1}=0
\end{aligned}
\right.$$it
下圖說明了 T2U 的轉換行爲:對於非負數(x ≥ 0), T2U 保留原值 :io
圖1. 從補碼到無符號數的轉換。函數 將負數轉換爲大的正數
函數 U2Tw(x) 定義爲 U2Tw(x) = B2Tw(U2Bw(x)) 。這個函數輸入的是一個 0 ~ 2(w-1)-1 之間的數,輸出則爲一個 -2w ~ 2(w-1) 之間的數。
上一節咱們已經獲得,對於負數(x < 0),T2U 被裝換爲一個大於2w − 1的正數。
反過來,咱們再來推導無符號數 u 和與之對應的有符號數 U2Tw(u)之間的關係。 利用上一節的結論, $B2T_w\left( \overrightarrow{u} \right) = B2U_w\left( \overrightarrow{u} \right) - u_{w-1} 2^w$ 。若令 $\overrightarrow{u} = U2B_w \left( u \right)$,則其反函數爲 $u = B2U_w \left( \overrightarrow{x} \right)$ 。由前面三式以及 T → B → U 變換的傳遞性,可得:
\begin{equation}B2T_w\left( U2B_w \left( u \right) \right) = U2T_w \left( u \right) = u - u_{w-1} 2^w \label{U2T} \end{equation}
在 u 原始的無符號表示法中,最高位uw − 1決定了 u 是否大於或等於 2w − 1, 無符數 u 到有符數的裝換分段表示爲:
$$ U2T_w \left( u \right)=\left\{
\begin{aligned}
& u, & u<2^{w-1},x_{w-1}=0 \\
& u-2^w, & x \leq 0,x_{w-1}=1
\end{aligned}
\right.$$
下圖說明了 U2T 轉換行爲:對於小的數(u < 2w − 1), U2T 保留原值 ; 對於大的數(u ≥ 2w − 1),U2T 被裝換爲一個負數:
圖2.從無符號數到補碼的轉換。函數U2T 把大於 的數字轉換爲負值
1.以下函數,在32bit系統中,求問foo(2^31-3)的值是:
int foo(int x) { return x&-x; }
A.0 B.1 C.2 D.4
解答:
y = x & (-x)
That does a bitwise AND between the variable x and its negation, and assigns the result to the variable y. If your system uses two's complement signed arithmetic , then what that manages to get you is the greatest power of 2 that is a factor of x. So, if x is 24, y gets assigned 8, and if x is 12, y gets assigned 4, and if x is 99, y becomes 1. To understand why it does that, you need to understand binary, and two's complement. Look them up on wikipedia.
reference