我有一个函数,它将多个位作为输入,并返回存储这些位所需的字节数:
unsigned int get_number_of_bytes(unsigned int number_of_bits);
因此,假设每字节8位:
number_of_bits
= 0 =>函数返回0 number_of_bits
= 1 =>函数返回1 number_of_bits
= 8 =>函数返回1 number_of_bits
= 9 =>函数返回2 可能的实施方式是:
unsigned int get_number_of_bytes(unsigned int number_of_bits)
{
if (number_of_bits == 0)
return 0;
else
return (number_of_bits - 1) / CHAR_BIT + 1;
}
(CHAR_BIT
通常等于8。)
如何在没有if
(并且没有?:
运算符)的情况下对此函数进行编码?
答案 0 :(得分:4)
unsigned int get_number_of_bytes(unsigned int number_of_bits)
{
return (number_of_bits + CHAR_BIT - 1) / CHAR_BIT;
}