gpt4 book ai didi

c - 如何反转字节顺序?

转载 作者:行者123 更新时间:2023-12-04 14:39:09 24 4
gpt4 key购买 nike

谁能帮我理解这段代码?

int reverse_endianess(int value) {
int resultat = 0;
char *source, *destination;
int i;

source = (char *) &value;
destination = ((char *) &resultat) + sizeof(int);
for (i = 0; i < sizeof(int); i++)
*(--destination) = *(source++);
return resultat;
}

我无法理解这部分代码:

destination = ((char *) &resultat) + sizeof(int);
for (i = 0; i < sizeof(int); i++)
*(--destination) = *(source++);

最佳答案

以下导致destination指向resultat之后的字节(只要resultat是一个int):

destination = ((char *) &resultat) + sizeof(int);

也可以这样写:

destination = (char *)(&resultat + 1);

下面只是一个简单的内存复制循环:

for (i = 0; i < sizeof(int); i++)
*(--destination) = *(source++);

等同于:

for (i = 0; i < sizeof(int); i++) {
--destination; // Point to the one byte earlier.
*destination = *source; // Copy one byte.
source++; // Point to one byte later.
}

程序流程(假设32位int和8位char)

设置后:

source               value
+----------+ +---+---+---+---+
| -------+ | a | b | c | d |
+----------+ | +---+---+---+---+
| ^
+------+

destination resultat
+----------+ +---+---+---+---+
| -------+ | 0 | 0 | 0 | 0 |
+----------+ | +---+---+---+---+
| ^
+----------------------+

循环一次后:

source               value
+----------+ +---+---+---+---+
| -------+ | a | b | c | d |
+----------+ | +---+---+---+---+
| ^
+----------+

destination resultat
+----------+ +---+---+---+---+
| -------+ | 0 | 0 | 0 | a |
+----------+ | +---+---+---+---+
| ^
+------------------+

完成后:

source               value
+----------+ +---+---+---+---+
| -------+ | a | b | c | d |
+----------+ | +---+---+---+---+
| ^
+----------------------+

destination resultat
+----------+ +---+---+---+---+
| -------+ | d | c | b | a |
+----------+ | +---+---+---+---+
| ^
+------+

关于c - 如何反转字节顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69303489/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com