Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is wrong with my algorithm?

Tags:

c

algorithm

math

Alright, I've cooked up some code to reverse hex characters around as part of a fun exercise I made up.

Here is what I have at the moment:

#include <stdio.h>  
int main() {  
    char a,b,c;  
    while (1) {  
        c = getchar();  
        if (!feof(stdin)) {  
            a = c % 16;  
            b = (c - a) / 16;  
            c = (a*16) + b;  
            putchar(c);  
        }else{break;}  
    }  
return 0;  
}  

It works well for most values. For example, 0xA0 becomes 0x0A etc...

However, it's not playing well with values beginning with 'F'.

0xF1 becomes 0x10
0xFF becomes 0xF0
etc...

Can somebody point me into the right direction?

like image 741
tangrs Avatar asked Feb 07 '10 07:02

tangrs


People also ask

What are the problems of algorithm?

Algorithms are commonly used to solve certain types of computational problems. We can often describe such a problem by specifying a relationship between input and output. The sorting problem, for example, can be described like this: Input: a sequence a1, a2, ..., an of n numbers.

Can an algorithm be wrong?

This increases the chances that test data used to build algorithms could be different from the real data they process, and that the decisions of the algorithm will be inaccurate or unfair. On top of this, all social data holds biases that an algorithm can end up replicating.

Is an algorithm always right?

As it turns out, it's difficult to prove that an algorithm is correct. Programmers often use empirical analysis to find faults in an algorithm, but only formal reasoning can prove total correctness.


2 Answers

If char is signed on your system, then when the upper nibble of c is f, c is negative, and c%16 will give a negative result.

like image 144
Neal Gafter Avatar answered Oct 21 '22 20:10

Neal Gafter


You're using a signed (on your machine) data type. Switch it to unsigned and it should works properly.

like image 31
akappa Avatar answered Oct 21 '22 20:10

akappa