這非常困難。我正在提取位來收集來自無符號字符數組的信息。有一部分我被卡住了。該數組有這四個字節:它包含0x79,0xE8,0x39,0x1A,我需要將它們反轉爲0x1A,0x39,0xE8,0x79。我reverse_order函數,而不是給我0x59,0x4,0x89,0x10(這是在陣列其他字節爲單位):c中的字節反轉順序
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>
#define LATITUDE_OFFSET 4
#define LONGITUDE_OFFSET 5
void reverse_order(unsigned char *start, unsigned char *end)
{
int i = 4;
do {
*start = *end;
++start;
--end;
--i;
} while(i > 0);
int j;
for(j=0; j<4; j++)
{
printf("the value: 0x%x\n", start[j]);
}
}
int main(void)
{
unsigned char msg[] = {
0x28,0x83,0x63,0x20,0x79,
0xE8,0x39,0x1A,0x59,0x04,
0x89,0x10,0x8D,0x2E,0xF1,
0x11,0x6E,0x00,0x10,0x8D,
0x51,0x57,0x29,0x0D
};
unsigned long long int time_secs;
unsigned char *start, *end;
int i, j;
//remove garbage
time_secs = 0;
i = 0;
while(msg[i] == 0x28)
{
++i;
}
unsigned char resp = ((msg[i] & 0xF) * 16) + 7;
unsigned char resp2 = (msg[i] & 0xF);
++i;
int unit_id_length = ((msg[i++] & 0xC0) >> 6)+1;
int is_latitude_south = (msg[i] & 0x10) >> LATITUDE_OFFSET;
int is_longitude_west = (msg[i] & 0x20) >> LONGITUDE_OFFSET;
++i;
start = &msg[i];
i+=3;
end = &msg[i];
reverse_order(start, end);
}
我標記你的答案是正確的,但出於好奇,你認爲使用memcpy可以更好地實現這樣的效果嗎? – JohnMerlino
@JohnMerlino我不認爲'memcpy()'在這裏很有幫助。 –