gpt4 book ai didi

更改 C 签名以接受字符数组而不是整数数组

转载 作者:行者123 更新时间:2023-11-30 17:51:51 26 4
gpt4 key购买 nike

首先我必须承认我不是 C 专家,而且在必须进行此类转换时我总是感到困惑。我有下一个函数,它接受前 2 个参数,2 个指向无符号整数数组的指针。如何更改算法以接受 2 个指向 无符号字符数组 的指针,并且当然可以对这 2 个字符指针数组进行操作? (我的意思是我知道不仅要更改签名,而且我还应该更改算法中的哪些内容?)

这就是我需要的:

void resize(unsigned char *input, unsigned char *output, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight) 

这就是我所拥有的:

void resize(unsigned int *input, unsigned int *output, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight) 
{
int a, b, c, d, x, y, index;
float x_ratio = ((float)(sourceWidth - 1)) / targetWidth;
float y_ratio = ((float)(sourceHeight - 1)) / targetHeight;
float x_diff, y_diff, blue, red, green ;
int offset = 0 ;

for (int i = 0; i < targetHeight; i++)
{
for (int j = 0; j < targetWidth; j++)
{
x = (int)(x_ratio * j) ;
y = (int)(y_ratio * i) ;
x_diff = (x_ratio * j) - x ;
y_diff = (y_ratio * i) - y ;
index = (y * sourceWidth + x) ;
a = input[index] ;
b = input[index + 1] ;
c = input[index + sourceWidth] ;
d = input[index + sourceWidth + 1] ;

// blue element
blue = (a&0xff)*(1-x_diff)*(1-y_diff) + (b&0xff)*(x_diff)*(1-y_diff) +
(c&0xff)*(y_diff)*(1-x_diff) + (d&0xff)*(x_diff*y_diff);

// green element
green = ((a>>8)&0xff)*(1-x_diff)*(1-y_diff) + ((b>>8)&0xff)*(x_diff)*(1-y_diff) +
((c>>8)&0xff)*(y_diff)*(1-x_diff) + ((d>>8)&0xff)*(x_diff*y_diff);

// red element
red = ((a>>16)&0xff)*(1-x_diff)*(1-y_diff) + ((b>>16)&0xff)*(x_diff)*(1-y_diff) +
((c>>16)&0xff)*(y_diff)*(1-x_diff) + ((d>>16)&0xff)*(x_diff*y_diff);

output [offset++] =
0x000000ff | // alpha
((((int)red) << 24)&0xff0000) |
((((int)green) << 16)&0xff00) |
((((int)blue) << 8)&0xff00);
}
}
}

最佳答案

原始代码有:

int a, b, c, d, x, y, index;
...

for (int i = 0; i < targetHeight; i++)
{
for (int j = 0; j < targetWidth; j++)
{
...
a = input[index] ;
b = input[index + 1] ;
c = input[index + sourceWidth] ;
d = input[index + sourceWidth + 1] ;

// blue element
blue = (a&0xff)*(1-x_diff)*(1-y_diff) + (b&0xff)*(x_diff)*(1-y_diff) +
(c&0xff)*(y_diff)*(1-x_diff) + (d&0xff)*(x_diff*y_diff);

// green element
green = ((a>>8)&0xff)*(1-x_diff)*(1-y_diff) + ((b>>8)&0xff)*(x_diff)*(1-y_diff) +
((c>>8)&0xff)*(y_diff)*(1-x_diff) + ((d>>8)&0xff)*(x_diff*y_diff);

// red element
red = ((a>>16)&0xff)*(1-x_diff)*(1-y_diff) + ((b>>16)&0xff)*(x_diff)*(1-y_diff) +
((c>>16)&0xff)*(y_diff)*(1-x_diff) + ((d>>16)&0xff)*(x_diff*y_diff);

greenred 的移位操作意味着代码假设来自 input 的每个值都有 3 个字节的数据,这当input的类型是unsigned int *时就可以了。但是,如果将输入类型更改为 unsigned char *,则必须决定是否只有蓝色数据(没有红色或绿色分量),或者是否有三个连续的字符提供蓝色、红色和绿色分量(或任何其他顺序;通常是 RGB,不是吗?),或者是否有其他排列。

如果您有 3 个连续的组件,则无需掩码 (& 0xFF),但您需要更频繁地访问该数组。

关于更改 C 签名以接受字符数组而不是整数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16485647/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com