Python vs C: different outputs

Question:

I have a small program that converts a base 10 number into a kind of a base 36 number. Here’s the Python code, and it works as expected.

def numToKey(num):
    start = 0x04;
    i = 0;
    for i in range(0,num):
        start+=1
    return start;


def largeNumToKeyboard(num):
    a = num / 1296;
    ar = num % 1296;
    b = ar / 36;
    c = ar % 36;

    a = numToKey(a);
    b = numToKey(b);
    c = numToKey(c);

    newb = b;
    if(a == b):
        newb = 0x2D;

    if(c == b):
        c = 0x2E;


    print a,newb,c
    print

largeNumToKeyboard(0)
largeNumToKeyboard(200)

The output is

4 45 46
4 9 24

“4 45 46” correctly represents 0, and “4 9 24” correctly represents 200.

But the issue is, it stops working after I convert it to C code.

#include <stdio.h>

int main(int argc, char **argv)
{
    printf("hello worldn");
    largeNumToKeyboard(0);
    largeNumToKeyboard(200);
    return 0;
}

char numToKey(char num) {
    char start = 0x04;
    char i = 0;
    for (i = 0; i < num; i++) {
        start++;
    }
    return start;
}

void largeNumToKeyboard(int num) {
    char a = num / 1296;
    char ar = num % 1296;
    char b = ar / 36;
    char c = ar % 36;

    a = numToKey(a);
    b = numToKey(b);
    c = numToKey(c);
    char newb = b;
    if(a == b){
        newb = 0x2D;
    }
    if(c == b){
        c = 0x2E;
    }
    printf("%d ",a);
    printf("%d ",newb);
    printf("%drn",c);

}

Now the output is

4 45 46
4 45 46

I don’t understand why for an input of 200, the C code gives me the wrong output, but the python code gives the correct output. I have a feeling it has something to do with the modulus, but I can’t figure it out. Please help! Thanks!

Asked By: Exastify

||

Answers:

In the C code you should use int types. char types only have a range from 0 to 255.

char a = num / 1296;
char ar = num % 1296;
char b = ar / 36;
char c = ar % 36; the C code 
Answered By: suspectus

Problem is you’re using char types in the void largeNumToKeyboard(int num) function, and the values you’re testing can potentially overflow a char. You’ll need to change at least the first three to int

void largeNumToKeyboard(int num) {
    int a = num / 1296;
    int ar = num % 1296;
    int b = ar / 36;
    char c = ar % 36;

    a = numToKey(a);
    b = numToKey(b);
    c = numToKey(c);
    char newb = b;
    if(a == b){
        newb = 0x2D;
    }
    if(c == b){
        c = 0x2E;
    }
    printf("%d ",a);
    printf("%d ",newb);
    printf("%drn",c);

}

…then it prints the output…

4 45 46
4 9 24
Answered By: Aya

In c code we should use int datatype as char gets overflow because it ranges from 0 to

Answered By: nishantsharma
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.