Advertisement
Guest User

Untitled

a guest
Mar 18th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.07 KB | None | 0 0
  1. /*Scrivere una function C che, fissato il numero n di bit, calcoli la rappresentazione di un intero:
  2. • per complemento a 2;
  3. • eccesso B (B-biased).*/
  4. #include<stdio.h>
  5. #include<stdlib.h>
  6. #include<string.h>
  7. #include<math.h>
  8. #define max_bit 16
  9.  
  10. void complemento_a_2(unsigned short numero_bit, unsigned short bit[max_bit], short x);
  11. void eccesso_B(unsigned short numero_bit, unsigned short bit[max_bit], short x);
  12. int main()
  13. {
  14.     unsigned short numero_bit, bit[max_bit];
  15.     short x;
  16.     printf("Inserisci il numero di bit = ");
  17.     scanf("%hu", &numero_bit);
  18.     printf("Inserisci il numero da rappresentare = ");
  19.     scanf("%hd", &x);
  20.     complemento_a_2(numero_bit, bit, x);
  21.     eccesso_B(numero_bit, bit, x);
  22.  
  23.     return 0;
  24. }
  25. void complemento_a_2(unsigned short numero_bit, unsigned short bit[max_bit], short x)
  26. ///I numeri vengono già memorizzati dalla macchina in complemento a 2
  27. {
  28.     char i;
  29.     for (i = max_bit - numero_bit - 1; i < max_bit; i++)
  30.     {
  31.         bit[i] = x & 1;
  32.         x = x >> 1;
  33.     }
  34.     printf("Rappresentazione in complemento a 2 = ");
  35.     for (i = max_bit - numero_bit - 1; i < max_bit; i++)
  36.         (i % 4 == 0) ? printf(" %hu", bit[i]) : printf("%hu", bit[i]);
  37.     printf("\n");
  38.     /*  char i;
  39.     for (i = 0; i < max_bit; i++) bit[i] = '0';
  40.     i = max_bit - 1;
  41.     do
  42.     {
  43.         bit[i] = (x % 2) + 48;
  44.         x = x / 2;
  45.         i--;
  46.     } while (x != 0 && i >= 0);
  47.     for (i = 0; i < max_bit; i++)
  48.     {
  49.         if (bit[i] == '0')
  50.             bit[i] = '1';
  51.         else
  52.             bit[i] = '0';
  53.     }
  54.     if (bit[max_bit-1] == '0')
  55.         bit[max_bit - 1] = '1';
  56.     else
  57.         bit[max_bit - 1] = '0';
  58.  
  59.     printf("In complemento a 2 = ");
  60.     for (i = max_bit - numero_bit - 1; i < max_bit; i++)
  61.         (i % 4 == 0) ? printf(" %c", bit[i]) : printf("%c", bit[i]);
  62.     printf("\n");*/
  63. }
  64. void eccesso_B(unsigned short numero_bit, unsigned short bit[max_bit], short x)
  65. {
  66.     char i;
  67.     x = x + (pow(2, numero_bit - 1) - 1);
  68.     i = max_bit - 1;
  69.     while (x > 0)
  70.     {
  71.         bit[i--] = x % 2;
  72.         x = x / 2;
  73.     }
  74.  
  75.     printf("Rappresentazione in Biased = ");
  76.     for (i = max_bit - numero_bit - 1; i < max_bit; i++)
  77.         (i % 4 == 0) ? printf(" %hu", bit[i]) : printf("%hu", bit[i]);
  78.     printf("\n");
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement