Muhammet Ömer
Muhammet Ömer

Reputation: 155

How do I translate function from Java to C?

We've been asked to build a library of random letters in Java. I did the homework. We are asked to write in C now. I did it with nanotime in Java. I did a little research, and I couldn't find nanotime in C.

Already tried in C: (It didn't work)

Random SayiOlustur(){
Random this;
this = (Random) malloc(sizeof(struct RANDOM));
char randomly;
int i;
struct timeval before , after;
gettimeofday(&before , NULL);
for (i=1 ; i <= 100 ; i++){
   printf("%d %d %d ",i, i*i, i*i*i);}
gettimeofday(&after , NULL);
printf("%d",Nano(before,after)); 
int random;
double test;
while(true){
    test = Nano(before,after);
    random = (int)test % (int)123.0;
    if((random >= 65 && random <= 90) || (random >= 97 && random <= 122)){
    randomly = (char) random;
    break;
    }}}
int Nano(struct timeval x,struct timeval y){
    double x_ms , y_ms , diff;
    x_ms = (double)x.tv_sec*1000000 + (double)x.tv_usec;
    y_ms = (double)y.tv_sec*1000000 + (double)y.tv_usec;
    diff = (double)y_ms - (double)x_ms;
    return diff;
}

Java Code: (working)

 private long Now(){
        long now = System.nanoTime();
        return now;
 }
public char Random(){
        char rastgele;
        while(true){
            random = (int)((Now())%123);
            // ASCI
            if((random >= 65 && random <= 90) || (random >= 97 && random <= 122))
                break;
        }
        rastgele = (char) random;
        return rastgele;
    }
public static void main(String[] args) {
        RastgeleKarakter rastgele = new RastgeleKarakter();
        System.out.println("Rastgele Karakter: " + rastgele.Random());
}

Out:

run:
Rastgele Karakter: m \\ Random

Out:

run
Rastgele Karakter: y \\ Random

Upvotes: 0

Views: 123

Answers (1)

One Guy Hacking
One Guy Hacking

Reputation: 1291

The Unix system call you are looking for is clock_gettime() which will give you nanosecond time.

That said, I'll offer some comments on on your C code even though you didn't ask: you would be better served to try to code from scratch instead of porting java code. Your system likely offers the random() call which will give you a random number far more cleanly than your approach. Also, you should never be casting the return from malloc(): it returns void *. Never cast if you can avoid it--it is a very bad habit that only ends up hiding bugs from you. Similarly, don't cast y_ms and x_ms to double--you declared them as doubles. That cast can only hurt you when you change the declaration of y_ms and x_ms and forget to change the cast.

You pass before and after to Nano(), which is bad. These are structures, so you are copying all the data in the structures onto the stack. It is far better to pass pointers to structures so you are only writing a pointer.

Upvotes: 2

Related Questions