csapp 2.64, 2.65

/* Return 1 when any odd bit of x equals 1; 0 otherwise. Assume w = 32 */

#include <stdio.h>

int any_odd_one(unsigned x)
{
    unsigned mask = 0xAAAAAAAA;
    return !!(x & mask);
}

int main(void)
{
    int result = any_odd_one(2);
    printf("result:%d\r\n", result);
    
    result = any_odd_one(3);
    printf("result:%d\r\n", result);
    
    return 1;
}

/*                                                                                                                                           
 * Return 1 when x contains an odd number of 1s; 0 otherwise.
 * Assume w=32.
 * 函数应遵循位级正数编码规则,不过你可以假设数据类型 int有 w=32位。
 * 你的代码最多只能包含12个算数运算、位运算和逻辑运算。
 */

int odd_ones(unsigned x)
{

    x ^= x>>16;
    x ^= x>>8;
    x ^= x>>4;
    x ^= x>>2;
    x ^= x>>1;

    x &= 1;

    return !!x;
}

int main(void)
{
    printf("result: %d \r\n", odd_ones(3));
    printf("result: %d \r\n", odd_ones(2));
    printf("result: %d \r\n", odd_ones(0xAAAAAAAA));
    printf("result: %d \r\n", odd_ones(0xAAAAAAA8));

    return 1;
}
posted @   铵铵静静  阅读(577)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示