啦啦啦拉拉裤 2021-10-06 15:28 采纳率: 69.4%
浏览 41
已结题

C语言问题,交换 16 位值的字节

望各位帮忙看看,现在就想要答案,蟹蟹各位潜水专家,感谢解答,感谢回答,感谢解答。在“PUT YOUR CODE HERE”写内容,前面内容不要改动,按照要求来编写。

// Swap bytes of a short

#include <stdint.h>
#include <stdlib.h>
#include <assert.h>

// given uint16_t value return the value with its bytes swapped
uint16_t short_swap(uint16_t value) {
    // PUT YOUR CODE HERE

    return 42;
}

img

  • 写回答

1条回答 默认 最新

  • 关注
    // Swap bytes of a short
    #include <stdint.h>
    #include <stdlib.h>
    #include <assert.h>
    #include <stdio.h>
    // given uint16_t value return the value with its bytes swapped
    uint16_t short_swap(uint16_t value)
    {
        uint16_t temp = 0x00FF;
        temp = temp & value;
        // printf("%x\n", temp);
        value = value >> 8;
        // printf("%x\n", value);
        value = value | (temp << 8);
        // printf("%x\n", value);
        return value;
    }
    int main(int argc, char const *argv[])
    {
        uint16_t a = 0x1234;
        printf("%x\n", short_swap(a));
        return 0;
    }
    

    img


    或者更简单的

    // Swap bytes of a short
    #include <stdint.h>
    #include <stdlib.h>
    #include <assert.h>
    #include <stdio.h>
    // given uint16_t value return the value with its bytes swapped
    uint16_t short_swap(uint16_t value)
    {
        return value << 8 | value >> 8;
    }
    int main(int argc, char const *argv[])
    {
        uint16_t a = 0x1234;
        printf("%x\n", short_swap(a));
        return 0;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 10月14日
  • 已采纳回答 10月6日
  • 创建了问题 10月6日