Advertisement
paperline27

HextoBinary

Jan 23rd, 2024
916
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.38 KB | Source Code | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. // Fungsi untuk mengonversi karakter heksadesimal ke nilai desimal
  6. int hexToDecimal(char hex) {
  7.     if (hex >= '0' && hex <= '9') {
  8.         return hex - '0';
  9.     } else if (hex >= 'A' && hex <= 'F') {
  10.         return hex - 'A' + 10;
  11.     } else if (hex >= 'a' && hex <= 'f') {
  12.         return hex - 'a' + 10;
  13.     } else {
  14.         return -1; // Mengembalikan -1 jika karakter tidak valid
  15.     }
  16. }
  17.  
  18. // Fungsi untuk mengonversi bilangan heksadesimal ke biner
  19. void hexToBinary(const char* hexString) {
  20.     printf("Hexadecimal: %s\nBinary: ", hexString);
  21.  
  22.     // Mengonversi setiap karakter heksadesimal ke biner
  23.     while (*hexString) {
  24.         int decimal = hexToDecimal(*hexString);
  25.  
  26.         if (decimal != -1) {
  27.             // Mengonversi nilai desimal ke biner
  28.             for (int i = 3; i >= 0; i--) {
  29.                 int bit = (decimal >> i) & 1;
  30.                 printf("%d", bit);
  31.             }
  32.         } else {
  33.             printf("Karakter heksadesimal tidak valid.\n");
  34.             return;
  35.         }
  36.  
  37.         hexString++;
  38.     }
  39.  
  40.     printf("\n");
  41. }
  42.  
  43. int main() {
  44.     char input[256];
  45.  
  46.     // Meminta input dari pengguna
  47.     printf("Masukkan bilangan heksadesimal: ");
  48.     scanf("%s", input);
  49.  
  50.     // Memanggil fungsi untuk mengonversi heksadesimal ke biner
  51.     hexToBinary(input);
  52.  
  53.     return 0;
  54. }
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement