I have done a little function that converts hex colour values to rgb values in c.
The function is working correctly, if I pass it in "#008080" I get:
HEX: #008080 RGB: 0, 128, 128
The issue I am having is when I am trying to print the value returned by pow() (for debugging purposes) this is what I get:
EX::: 0
POWER::: 0.000000
EX::: 1
POWER::: 0.000000
EX::: 0
POWER::: 0.000000
EX::: 1
POWER::: 0.000000
EX::: 0
POWER::: 0.000000
EX::: 1
POWER::: 0.00000
This is the code that outputs this:
int num = 0;
char c;
double power;
for (int i = strlen(hexString), ex = 0; i > 0; i--, ex++) {
c = hexString[i - 1];
power = pow(16.0, ex);
printf("EX::: %d\n", ex);
printf("POWER::: %lf\n", power);
num += convertHexCharToDec(&c) * power;
}
If I run this with GDB I can see that the power variable has the values of 1 and then 16.
What is the problem here? The function outputs the correct value, I can see the correct value in the debugger so why can't I see the correct values??
Thanks
Edit: Added power variable type
Edit2: After messing a bit more with printfs specifiers I discovered that I should have used %f specifier.
Thanks for the help.
You should first check the type of power
, which you haven't shown.
Disagreements between format specifiers and the variables you pass to printf
are undefined behaviour, which is why:
#include <stdio.h>
int main (void) {
int i = 42;
double d = 3.14159;
printf("POWER::: %lf\n", i);
printf("POWER::: %lf\n", d);
return 0;
}
can give you:
POWER::: 0.000000
POWER::: 3.141590
with impunity.
For a more detailed reason why these incorrect results can happen, see this answer . It doesn't specifically cover floating point values but the theory is the same. If you tell printf
to expect one thing then give it a totally different thing, you can hardly complain if it becomes confused :-)
If power
is an integral type, you need to either change it to a non-integral type, or change the format specifier. One way or another, they should match.
In any case, you don't need to resort to floating point at all for this task provided you have a 32-bit integer (and the color codes are all 24-bit). You can just use code like:
for (int i = strlen(hexString), mult = 1; i > 0; i--, mult *= 16) {
c = hexString[i - 1];
printf("MULT::: %d\n", mult);
num += convertHexCharToDec(&c) * mult;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.