[Oberon] ReadNum and WriteNum in C

Jörg Straube joerg.straube at iaeth.ch
Mon Jul 11 15:14:26 CEST 2016


Srinivas

Coming back to your request how to program WriteNum and ReadNum in C.
Did not compile it on a machine but this code should do:


void WriteNum(FILE* R, int x)
{
  unsigned char b;

  for(;;)
  {
    b = x & 0x7f;
    if ( (x < -0x40) || (0x40 <= x) ) break;
    fputc(0x80 | b, R); x >>= 7;
  }
  fputc(b, R);
}


void ReadNum(FILE* R, int* x)
{
  unsigned char b;
  int y=0, shift=0;

  do
  {
    b = fgetc(R); y |= (b & 0x7f) << shift; shift += 7;
  }
  while (b >= 0x80);
  if (b >= 0x40) y |= -1 << shift;
  *x=y
}


Jörg



Gruss, Jörg
> Am 09.07.2016 um 14:43 schrieb Srinivas Nayak <sinu.nayak2001 at gmail.com>:
> 
> Dear All,
> 
> Here I tried to implement ReadNum and WriteNum in C.
> I couldn't do it simply using / and % imitating
> how NW has written them using DIV and MOD and Shifts.
> I would like to see a better way to do it...
> 
> 
> #include <stdio.h>
> 
> #define ELSIF  }else if(
> #define ELSE   }else{
> #define IF     if(
> #define THEN   ){
> #define END    }
> #define WHILE  while(
> #define DO     ){
> #define REPEAT do{
> #define UNTIL  }while(!(
> #define RETURN return
> 
> unsigned int ROR(unsigned int x, int n)
> {
>    return (x >> (n%32))|(x << ((32-n)%32));
> }
> 
> int ASR(int x, int n)
> {
>    return (x >> n%32);
> }
> 
> void ReadNum(FILE* R, int* x)
> {
>    int y, n;
>    unsigned char b;
>    n = 32; y = 0;
>    b = fgetc(R);
>    //printf("%hhu ", b);
> 
>    WHILE b >= 0x80 DO
>        y = ROR(y|(b-0x80), 7);
>        n = n-7;
>        b = fgetc(R);
>        //printf("%hhu ", b);
>    END
> 
>    //printf("\n");
> 
>    IF n <= 4 THEN
>        *x = ROR(y|(b&0xF), 4);
>    ELSE
>        *x = ASR(ROR(y|b, 7), n-7);
>    END
> }
> 
> void WriteNum(FILE* R, int x)
> {
>    unsigned char b;
> 
>    WHILE (x < -0x40) || (x >= 0x40) DO
>        b = (x & 0x7F)|0x80;
>        fputc(b, R);
>        //printf("%hhu ", b);
>        x = ASR(x, 7);
>    END
> 
>    b = (x & 0x7F);
>    fputc(b, R);
>    //printf("%hhu ", b);
>    //printf("\n");
> }
> 
> 
> int main()
> {
>    FILE *f;
>    int i = 0;
>    int m = 0, n = 0;
> 
>    for (i = -8192; i <= 8192; i++)
>    {
>        m = i;
>        //printf("\nnum write = %d\n", m);
>        f = fopen("test.bin", "wb");
>        WriteNum(f, m);
>        fclose(f);
> 
>        f = fopen("test.bin", "rb");
>        ReadNum(f, &n);
>        fclose(f);
>        //printf("num read = %d\n", n);
> 
>        if(m != n)
>        {
>            printf("%d FAILED\n", m);
>        }
>    }
> 
>    return 0;
> }
> 
> 
> 
> With thanks and best regards,
> 
> Yours sincerely,
> Srinivas Nayak
> 
> Home: http://www.mathmeth.com/sn/
> Blog: http://srinivas-nayak.blogspot.in/
> --
> Oberon at lists.inf.ethz.ch mailing list for ETH Oberon and related systems
> https://lists.inf.ethz.ch/mailman/listinfo/oberon



More information about the Oberon mailing list