我需要在C中将int转换为unsigned char.如果int> 255 char将是255,如果in <0 char将为0.否则char等于int.我怎么用C做到这一点?
我试过了:
int i;
unsigned char c;
c = (unsigned char) i;
Run Code Online (Sandbox Code Playgroud)
但它尚未奏效(它包裹,即c = i%256).
只需编写您想要的代码.
unsigned char convert(int j)
{
if (j >= 255) return 255;
if (j < 0) return 0;
return (unsigned char) j;
}
Run Code Online (Sandbox Code Playgroud)
这可能会更好(在我的机器上,6条指令,没有分支),特别是如果大多数值在0-255范围内:
unsigned char convert(int j)
{
unsigned char j2 = (unsigned char) j;
if (j == j2) return j2;
return (j < 0) ? 0 : 255;
}
Run Code Online (Sandbox Code Playgroud)