[Oberon] ReadNum and WriteNum in C
Frans-Pieter Vonck
fp at vonck.nl
Sat Jul 9 19:58:33 CEST 2016
Hi Srinivas,
great fun to give C some Algol swag!
the superfluous ";" in the while loop
can the it be removed by
#define END ;}
?
Greets,
F.P.
Srinivas Nayak schreef op 2016-07-09 14:43:
> 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