工程師應知道的0x10個問題(13): 0的一補數

MuLong PuYang
4 min readMar 19, 2022

--

英文參考網址

A ‘C’ Test: The 0x10 Best Questions for Would-be Embedded Programmers

中文參考網址

C語言測試 應知道的0x10個基本問題

原文翻譯

13. Comment on the following code fragment?

評論以下的程式碼片段?

unsigned int zero = 0;

unsigned int compzero = 0xFFFF; /*1’s complement of zero */

On machines where an int is not 16 bits, this will be incorrect. It should be coded:

當一個機器不是16位元的,這個會導致錯誤。它應該被寫成這樣:

unsigned int compzero = ~0;

This question really gets to whether the candidate understands the importance of word length on a computer. In my experience, good embedded programmers are critically aware of the underlying hardware and its limitations, whereas computer programmers tend to dismiss the hardware as a necessary annoyance.

這個問題真的可以知道應試者是否了解字組長度在電腦的重要性。在我的經驗中,好的嵌入式程式設計師會嚴謹的知道硬體的細節與它的限制,然後電腦程式設計師傾向忽視硬體並把它視為一個必要的煩擾。

注1: 這裡的the underlying hardware我覺得中文來源翻得蠻好的,因為underlying本身有基本的與潛在的意思在,中文來源翻成硬體的細節我覺得是個好的翻法故在此採用注2: dismiss the hardware as a necessary annoyance這裡中文來源翻成"然而PC機程式往往把硬體作為一個無法避免的煩惱",但是dismiss本身有忽視的意思在,所以我這邊會傾向翻成忽視硬體並把硬體視為一個必要的煩惱,這裡如果讀者覺得有更好的譯法,歡迎再留言跟我說

By this stage, candidates are either completely demoralized — or they are on a roll and having a good time. If it is obvious that the candidate isn’t very good, then the test is terminated at this point. However, if the candidate is doing well, then I throw in these supplemental questions. These questions are hard, and I expect that only the very best candidates will do well on them. In posing these questions, I’m looking more at the way the candidate tackles the problems, rather than the answers. Anyway, have fun…

到了這個階段,應試者會完全的沮喪我或者是連連獲勝以及有個好時光。如果明顯的應試者不是非常好,那麼這個測驗將在這裡結束。然而,如果應試者做得好,那麼我將丟出這些追加的問題。這些問題算難,而且我預期只有非常好的應試者會做好它們。提出這些問題後,我更側重的是應試者處理這些問題,而不是答案。不管怎樣,玩得開心…

自我實作以及理解

注1: 以下是我的自我實作以及理解的部分,不保證正確而且很有可能描述不清楚或者是有錯誤,讀者若發現有可以更正的地方也歡迎留言告訴我注2: 以下皆簡單的使用Ubuntu 20.04虛擬機做測試,並非真實的嵌入式系統,所以Ubuntu 20.04出來的成果可能會與嵌入式系統上的有差異注2: 以下皆簡單的使用Ubuntu 20.04虛擬機做測試,並非真實的嵌入式系統,所以Ubuntu 20.04出來的成果可能會與嵌入式系統上的有差異

原文中compzero被設為0xFFFF,但是事實上機器有可能不是16位元

unsigned int compzero = 0xFFFF;

像我這邊用的是64位元系統,int為32位元,我們用以下程式碼執行過後可以發現

輸出結果我們可以看到在Ubuntu 64位元的系統上,我們可以發現0的一補數其實是0xffffffff,而不是0xfffff,所以要得到正確的一補數,用~0是個安全的做法

copmzero: ffff
compzero_with_tilde: ffffffff

--

--