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?
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.
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.
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.
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.
You're using a signed (on your machine) data type. Switch it to unsigned and it should works properly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With