fork download
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <math.h>
  4. #include <stdint.h>
  5.  
  6. // ฟังก์ชันแปลง Binary ไปเป็น Gray Code
  7. unsigned char binaryToGray(unsigned char num) {
  8. return num ^ (num >> 1);
  9. }
  10.  
  11. // ฟังก์ชันแปลง Binary ไปเป็น Signed Decimal (2's complement)
  12. int binaryToSigned(char *binary) {
  13. int result = 0;
  14. if (binary[0] == '1') { // msb = 1 คือเลขลบ
  15. for (int i = 0; i < 8; i++) {
  16. result = result * 2 + (binary[i] == '0' ? 1 : 0);
  17. }
  18. result = -(result + 1);
  19. } else {
  20. for (int i = 0; i < 8; i++) {
  21. result = result * 2 + (binary[i] - '0');
  22. }
  23. }
  24. return result;
  25. }
  26.  
  27. // ฟังก์ชันแปลง Binary ไป Fixed Point [4.4]
  28. float binaryToFixedPoint(char *binary) {
  29. float result = 0.0;
  30. int int_part = 0, frac_part = 0;
  31.  
  32. // คำนวณส่วนจำนวนเต็ม (4 บิตแรก)
  33. for (int i = 0; i < 4; i++) {
  34. int_part = int_part * 2 + (binary[i] - '0');
  35. }
  36.  
  37. // คำนวณส่วนทศนิยม (4 บิตสุดท้าย)
  38. for (int i = 4; i < 8; i++) {
  39. frac_part = frac_part * 2 + (binary[i] - '0');
  40. }
  41.  
  42. result = int_part + (frac_part / 16.0); // 2^4 = 16
  43. return result;
  44. }
  45.  
  46. int main() {
  47. char binary[9]; // เก็บเลข 8 บิต + null terminator
  48. printf("Enter a binary code [8-bit]: ");
  49. scanf("%8s", binary);
  50.  
  51. // แปลง binary เป็น unsigned decimal
  52. unsigned char num = (unsigned char)strtol(binary, NULL, 2);
  53.  
  54. printf("unsigned decimal : %u\n", num);
  55. printf("octal : %o\n", num);
  56. printf("hexadecimal : %X\n", num);
  57.  
  58. // แปลง binary เป็น signed decimal
  59. int signedNum = binaryToSigned(binary);
  60. printf("signed decimal (2's complement): %d\n", signedNum);
  61.  
  62. // แปลง binary เป็น Gray Code
  63. unsigned char grayCode = binaryToGray(num);
  64. printf("gray code: %u [%08b]\n", grayCode, grayCode);
  65.  
  66. // แปลง binary เป็น Fixed Point [4.4]
  67. float fixedPoint = binaryToFixedPoint(binary);
  68. printf("fixed point [4.4]: %.6f\n", fixedPoint);
  69.  
  70. return 0;
  71. }
  72.  
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
Enter a binary code [8-bit]: unsigned decimal : 0
octal            : 0
hexadecimal      : 0
signed decimal (2's complement): -11958
gray code: 0 [%08b]
fixed point [4.4]: -747.375000