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

// 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;
}