0

I am trying to convert between a double, which is between 0 and 1, and an unsigned char for the processing of an image.

What I'm doing so far is I have an array of floats.

float array[length*4]

with the 4 coming from the RGBA color scheming system. I then try this:

unsigned char newArray[4*length]
for (int i=0; i<4*length; i++){
    newArray[i] = 255*array[i];
}

for (int i=0; i<10; i++){
    printf("newArray: %d", newArray[i])
}

and get the following output:

newArray: 32
newArray: 128
newArray: 131
newArray: 0
newArray: 173
newArray: 224
newArray: 56
newArray: 60
newArray: 125
newArray: 104

when it should be this:

should be: 0
should be: 75
should be: 140
should be: 255
should be: 1
should be: 79
should be: 143
should be: 255
should be: 1
should be: 84
should be: 150
should be: 255

I have tried other methods, but they don't work.

My question to you is: how do I convert between a float and an unsigned char?

EDIT: The code that generated the correct output is this:

for (i=0; i<length; i++) {
    [[data objectAtIndex:i] getRed:&red green:&green blue:&blue alpha:&alpha];
    array[i][0] = 255*red;
    array[i][1] = 255*green;
    array[i][2] = 255*blue;
    array[i][3] = 255*alpha;

}

for (i=0; i<10; i++) {
    NSLog(@"before: %f, %f, %f, %f", array[i][0],array[i][1],array[i][2],array[i][3]);
}

, where all I did was edit the output so it was

1
2
3
4

instead of 1,2,3,4.

4

1 回答 1

0

转换此代码:

for (int i=0; i<4*length; i++){
    newArray[i] = 255*array[i];
}

对此:

for (int i=0; i<4*length; i++)
{
    float f = 255*array[i];
    if (f < 0 || f > 255)
    {
      printf("error, array[%d]=%f, 255*array[%d]=%f\n!", i, array[i], i, f);
      abort();
    }
    newArray[i] = f;
}

它会告诉你你的浮点数不在 0 到 1 的范围内。

于 2012-10-14T21:13:42.320 回答