#include <stdio.h>
#include <math.h>
// ฟังก์ชันแปลงเลขฐานสองเป็น Gray Code
unsigned int binaryToGray(unsigned int num) {
return num ^ (num >> 1); // ใช้การ XOR กับการเลื่อนบิต 1 ตำแหน่ง
}
// ฟังก์ชันแปลงเลขฐานสองเป็น Signed Decimal (2's complement)
int binaryToSigned(int num, int bits) {
if (num & (1 << (bits - 1))) { // ตรวจสอบ MSB
num -= (1 << bits); // ถ้า MSB=1 ให้ลบออกจากจำนวนเต็ม
}
return num;
}
// ฟังก์ชันแปลงเลขฐานสองเป็น Fixed Point [4.4]
double binaryToFixedPoint(int num) {
return num / 16.0; // แบ่งด้วย 2^4 (16) เนื่องจาก [4.4] หมายถึงทศนิยม 4 หลัก
}
int main() {
char binary[9]; // รับเลข 8 บิต (พร้อม '\0')
unsigned int decimal = 0; // เก็บค่าเป็น unsigned decimal
int bits = 8; // จำนวนบิต 8 บิต
// รับค่าจากผู้ใช้
printf("Enter a binary code [8-bit]: ");
// แปลงจาก String Binary เป็น Unsigned Decimal
for (int i = 0; i < bits; i++) {
if (binary[i] == '1') {
decimal += (1 << (bits - 1 - i));
}
}
// แปลงเป็น Signed Decimal (2's complement)
int signedDecimal = binaryToSigned(decimal, bits);
// คำนวณ Gray Code
unsigned int grayCode = binaryToGray(decimal);
// คำนวณ Fixed Point [4.4]
double fixedPoint = binaryToFixedPoint(decimal);
// แสดงผลลัพธ์
printf("unsigned decimal : %u\n", decimal
); printf("octal: %o\n", decimal
); printf("hexadecimal: %X\n", decimal
); printf("signed decimal (2's complement): %d\n", signedDecimal
); printf("gray code: %u [%08d]\n", grayCode
, grayCode
); printf("fixed point [4.4]: %.5lf\n", fixedPoint
);
return 0;
}
I2luY2x1ZGUgPHN0ZGlvLmg+CiNpbmNsdWRlIDxtYXRoLmg+CgovLyDguJ/guLHguIfguIHguYzguIrguLHguJnguYHguJvguKXguIfguYDguKXguILguJDguLLguJnguKrguK3guIfguYDguJvguYfguJkgR3JheSBDb2RlCnVuc2lnbmVkIGludCBiaW5hcnlUb0dyYXkodW5zaWduZWQgaW50IG51bSkgewogICAgcmV0dXJuIG51bSBeIChudW0gPj4gMSk7IC8vIOC5g+C4iuC5ieC4geC4suC4oyBYT1Ig4LiB4Lix4Lia4LiB4Liy4Lij4LmA4Lil4Li34LmI4Lit4LiZ4Lia4Li04LiVIDEg4LiV4Liz4LmB4Lir4LiZ4LmI4LiHCn0KCi8vIOC4n+C4seC4h+C4geC5jOC4iuC4seC4meC5geC4m+C4peC4h+C5gOC4peC4guC4kOC4suC4meC4quC4reC4h+C5gOC4m+C5h+C4mSBTaWduZWQgRGVjaW1hbCAoMidzIGNvbXBsZW1lbnQpCmludCBiaW5hcnlUb1NpZ25lZChpbnQgbnVtLCBpbnQgYml0cykgewogICAgaWYgKG51bSAmICgxIDw8IChiaXRzIC0gMSkpKSB7IC8vIOC4leC4o+C4p+C4iOC4quC4reC4miBNU0IKICAgICAgICBudW0gLT0gKDEgPDwgYml0cyk7ICAgICAgICAvLyDguJbguYnguLIgTVNCPTEg4LmD4Lir4LmJ4Lil4Lia4Lit4Lit4LiB4LiI4Liy4LiB4LiI4Liz4LiZ4Lin4LiZ4LmA4LiV4LmH4LihCiAgICB9CiAgICByZXR1cm4gbnVtOwp9CgovLyDguJ/guLHguIfguIHguYzguIrguLHguJnguYHguJvguKXguIfguYDguKXguILguJDguLLguJnguKrguK3guIfguYDguJvguYfguJkgRml4ZWQgUG9pbnQgWzQuNF0KZG91YmxlIGJpbmFyeVRvRml4ZWRQb2ludChpbnQgbnVtKSB7CiAgICByZXR1cm4gbnVtIC8gMTYuMDsgLy8g4LmB4Lia4LmI4LiH4LiU4LmJ4Lin4LiiIDJeNCAoMTYpIOC5gOC4meC4t+C5iOC4reC4h+C4iOC4suC4gSBbNC40XSDguKvguKHguLLguKLguJbguLbguIfguJfguKjguJnguLTguKLguKEgNCDguKvguKXguLHguIEKfQoKaW50IG1haW4oKSB7CiAgICBjaGFyIGJpbmFyeVs5XTsgICAgICAgICAgI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