2016-11-07 37 views
-1

我知道有符號整數和無符號整數之間的區別在於解釋整數的高位比特。 如果有指定的有符號整數,則C編譯器生成代碼,假定高位用作符號標誌。C中的高位比特

編譯器如何使用高位作爲符號標誌?

當我寫signed int num = 23;時,它在二進制格式的內存中看起來如何?

謝謝。

+0

取決於即使它符號或無符號的CPU上:見大端endian和little-endian。 – nicomp

+0

還有更多的因素。目標體系結構使用哪種endianess? –

+0

系統的Endianness被用來確定哪個是高位或低位 – smac89

回答

2

整數意味着什麼是高階位或低階位?

當您從左向右寫入數字的二進制表示的位時,包括前導零(如果有的話),最左邊的位是高位;最右邊的位是低位。

當有指定的有符號整數時,C編譯器生成的代碼假定高位被用作符號標誌? 編譯器如何使用高位作爲符號標誌?

這是特定於編寫編譯器的硬件。其原因是負數的表示與CPU的算術單元結合在一起,它產生特定於給定硬件的負數表示。

當我寫入signed int num = 23時,它在內存中的外觀如何?

由於數是23,在存儲器中它的符號表示的是相同的23無符號表示,即0x00000017十六進制與4字節的整數的計算機上的。

2

除了由daslinkenlight提供的很好的答案外,這裏還有一個玩具程序程序,它打印整型的二進制表示。

例C++代碼:

#include <climits> 
#include <iostream> 
#include <iomanip> 
#include <string> 
#include <type_traits> 

template<typename T, 
     typename = typename std::enable_if<std::is_integral<T>::value, T>::type> 
std::string get_raw_bytes(T t) { 
    const auto limit = sizeof(T) * CHAR_BIT; 
    std::string bits(limit, '0'); 
    for(auto i = 0; i < limit; i++) { 
    bits[limit - i - 1] = ((t >> i) & 1) ? '1' : '0'; 
    } 
    return bits; 
} 

int main() { 
    std::cout << "Integers:\n"; 
    for (int i = -5 ; i < 6 ; i++) { 
    std::cout << std::setw(4) << i << " " << get_raw_bytes(i) << '\n'; 
    } 

    std::cout << "Character:\n"; 
    std::cout << std::setw(4) << (char)104 << " " << get_raw_bytes<char>(104) << '\n'; 
} 

例C代碼:

#include <stdio.h> 
#include <stdlib.h> 
#include <limits.h> 

#define INT_BITS (sizeof(int) * CHAR_BIT) 

void get_int_raw_bytes(int in, char* out) { 
    for (unsigned long i = 0 ; i < INT_BITS ; i++) { 
    out[INT_BITS - i - 1] = ((in >> i) & 1) ? '1' : '0'; 
    } 
} 

void get_char_raw_bytes(char in, char* out) { 
    for (unsigned long i = 0 ; i < CHAR_BIT ; i++) { 
    out[CHAR_BIT - i - 1] = ((in >> i) & 1) ? '1' : '0'; 
    } 
} 

int main() { 
    puts("Integers:"); 
    for (int i = -5 ; i < 6 ; i++) { 
    char buffer[INT_BITS + 1]; 
    buffer[INT_BITS] = '\0'; 
    get_int_raw_bytes(i, buffer); 
    printf("%4.d %s\n", i, buffer); 
    } 
    puts("Character:"); 
    char buffer[CHAR_BIT + 1]; 
    buffer[CHAR_BIT] = '\0'; 
    get_char_raw_bytes(104, buffer); 
    printf("%4.c %s\n", 104, buffer); 
} 

隨着輸出示例:

Integers: 
    -5 11111111111111111111111111111011 
    -4 11111111111111111111111111111100 
    -3 11111111111111111111111111111101 
    -2 11111111111111111111111111111110 
    -1 11111111111111111111111111111111 
    0 00000000000000000000000000000000 
    1 00000000000000000000000000000001 
    2 00000000000000000000000000000010 
    3 00000000000000000000000000000011 
    4 00000000000000000000000000000100 
    5 00000000000000000000000000000101 
Character: 
    h 01101000 
+1

AGH!我以爲我有C++過濾器!無論哪種方式,問題的關鍵是_is_語言不可知論:(......也許我會修復它是C. – druckermanly

+0

@RadLexus感謝您的領導。我已經(幾乎)在兩者之間取得平衡。至少,足以讓我滿足於結果。 :) – druckermanly