Number System and Code

1.បំលែងពី Binary Code ទៅជា Gray Code ដោយសសេរកូតនៅក្នុង C programm

សួស្ដីអ្នកទាំងអស់គ្នានេះគឺជាកូតសំរាប់ធ្វើការបំលែងពី Binary Code ទៅជា Gray Code
តើអ្វីជា Binary Code ?
Binary Code គឺជាប្រព័ន្ធគោលពីរដែលមានន័យថាវាប្រើចំនួន ០ នឹង ១ ដើម្បីទំនាក់ទំនងព័ត៍មាន
Binary Code គឺត្រូវបានប្រើជាតំណាងអោយសៀគ្វីនៅក្នុង Digital
តើអ្វីជា Gray Code ?
Gray Code គឺជា Code non-weighted(ដែលមិនអាចគណនាបាន) Binary code ហើយលក្ខណះពិសេសគឺជាវាប្រែប្រួលតែ1 Bit ហើយគេប្រើប្រាស់វាដើម្បីជួយកាត់បន្ថយការ Errors នៅក្នុងសៀគ្វី Digital
ខាងក្រោមនេះជាកូត C program សំរាប់ធ្វើការគណនារឺបំលែងពី Binary Code ទៅជា Gray Code
ដោយគ្រាន់តែ Copy ទៅក្នុង IDE ហើយ Paste បន្ទាប់មកជាការស្រេច

# include<stdio.h>
# include<conio.h>
# include<stdlib.h>
static int a[8],b[8],k=1,i;
void main()
{   int n1;
clrscr();
printf("Enter any Numbers :");
scanf("%d",&n1);
while(n1!=0)   /* converting number to its binary equivalent */
{  a[i]=n1 % 2;
n1/=2;
i++;
}
/* printing binary equivalent */
printf("\nThe binary code of the given number is :");
for(i=7;i>=0;i--)
printf("%d",a[i]);




/* gray code conversion */
b[0]=a[7];


for(i=7;i>=0;i--)
{  if(a[i]==0 && a[i-1]==0)
b[k]=0;
if(a[i]==1 && a[i-1]==1)
b[k]=0;
if(a[i]==0 && a[i-1]==1)
b[k]=1;
if(a[i]==1 && a[i-1]==0)
b[k]=1;
k++;
}


/* printing the gray code */
printf("\nThe gray code of the given number is :");
for(i=0;i<8;i++)
printf("%d",b[i]); 
    getch();
}


2.កម្មវិធី Covert Binary ទៅ Decimal(គោល១០),Hexadecimal(គោល16),ហើយ Octal (គោល៨)


#include <stdio.h>
#include <string.h>

int bin2dec(char *bin);

int main()
{
  char bin[80] = "";
  char *p;
  int  dec;

  while(strcmp(bin,"0"))
  {
    printf("\n Enter a binary number (just 0 to EXIT): ");
    fgets(bin, sizeof(bin), stdin);
    // check for and remove trailing \n
    if ((p = strchr(bin,'\n')) != NULL)
    {
      *p = '\0';
    }
    dec = bin2dec(bin);
    if (dec) printf("\nDecimal = %d  Hexadecimal = 0x%04X  Octal = 0%o\n",dec,dec,dec);
  }

  getchar();  // wait
  return 0;
}

// convert a binary string to a decimal number, returns decimal value
int bin2dec(char *bin)  
{
  int  b, k, m, n;
  int  len, sum = 0;

  len = strlen(bin) - 1;
  for(k = 0; k <= len; k++)
  {
    n = (bin[k] - '0'); // char to numeric value
    if ((n > 1) || (n < 0))
    {
      puts("\n\n ERROR! BINARY has only 1 and 0!\n");
      return (0);
    }
    for(b = 1, m = len; m > k; m--)
    {
      // 1 2 4 8 16 32 64 ... place-values, reversed here
      b *= 2;
    }
    // sum it up
    sum = sum + n * b;
    //printf("%d*%d + ",n,b);  // uncomment to show the way this works
  }
  return(sum);
}