Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

การจัดเก็บค่า Integer และ Character ในหน่วยความจำ C

ใน C ตัวอักษรก็เก็บเป็น Integer (ASCII) เช่นกัน การเก็บค่าที่เกินขนาด char จะเกิด Overflow และเก็บเฉพาะ 8-bit ล่าง

ตัวอย่าง

#include <stdio.h>

int main() {
    char x = 270;   // Binary: 1 0000 1110 -> 取 8 bit: 0000 1110 = 14
    char y = -130;  // 2's complement ของ 130 -> เก็บ 8 bit ล่าง = 126
    printf("The value of x is: %d\n", x);
    printf("The value of y is: %d", y);
    return 0;
}

ผลลัพธ์

The value of x is: 14
The value of y is: 126

คำอธิบาย

  • 270 = 0x10E -> 取 low 8 bits = 0x0E = 14
  • -130: 130 = 0x82 -> 2's complement = 0x7E = 126