我有一个“疯狂”的时刻 - 我无法在 XC8 中将sprintf(32 位)打印为十六进制。
因此,我将相关代码部分剪切并粘贴到在线 C 编译器中,在那里它工作正常:
C:
#include 《stdio.h》
char text[9];
// Func
tion to reverse bits of num
unsigned char reverseBits(unsigned char num)
{
//unsigned char NO_OF_BITS = sizeof(num) * 8;
unsigned char reverse_num = 0, i, temp;
for (i = 0; i 《 8; i++)
{
temp = (num & (1 《《 i));
if(temp)
reverse_num |= (1 《《 ((7) - i));
}
return reverse_num;
}
int main() {
unsigned long nec_code = 0x18E708F7;
unsigned long fullcode = nec_code;
unsigned int address16 = nec_code 》》 16;
unsigned int command16 = nec_code & 0xFFFF;
unsigned char address = nec_code 》》 24;
unsigned char inv_address = nec_code 》》 16;
unsigned char command = nec_code 》》 8;
unsigned char inv_command = nec_code;
// reverse codes to correct values
command=reverseBits(command);
inv_command=reverseBits(inv_command);
address=reverseBits(address);
inv_address=reverseBits(inv_address);
//address16=reverseBits16(address16);
sprintf(text,“%08X”,fullcode);
printf(“Full code: 0x%s\n”, text); // print nec_code
sprintf(text,“%04X”,nec_code》》 16);
printf(“NEC code: 0x%s”, text); // print nec_code
sprintf(text,“%04X”,nec_code & 0xFFFF);
printf(“%s\n”, text); // print nec_code
sprintf(text,“%04X”,address16);
printf(“Address16: 0x%s\n”, text); // print address16
sprintf(text,“%04X”,command16);
printf(“Command16: 0x%s\n”, text); // print command16
sprintf(text,“%02X”,address);
printf(“Address: 0x%s\n”, text); // print address
sprintf(text,“%02X”,inv_address);
printf(“Inverted: 0x%s\n”, text); // print inv_address
sprintf(text,“%02X”,command);
printf(“Command: 0x%s\n”, text); // print command
sprintf(text,“%02X”,inv_command);
printf(“Inverted: 0x%s\n\r”, text); // print inv_command
}
Result:
Full code: 0x18E708F7
NEC code: 0x18E708F7
Address16: 0x18E7
Command16: 0x08F7
Address: 0x18
Inverted: 0xE7
Command: 0x10
Inverted: 0xEF
Same result in XC8:
Full code: 0x000008F7
NEC code: 0x18E708F7
Address16: 0x18E7
Command16: 0x08F7
Address: 0x18
Inverted: 0xE7
Command: 0x10
Inverted: 0xEF
该代码是我目前对红外遥控器进行实验的一部分,这次是 NEC 遥控器。NEC 遥控器的输出是 32 位,前 8 位是地址,第二个 8 位相同但反转,然后是 8 位命令,然后是反转命令。所有最低有效位都排在第一位,因此是翻转顺序的例程,以给出“正确”的值。
我可以剥离两个 16 位值,并将它们组合起来以显示 32 位值(第二行),但为什么第一行不适用于 XC8(C90 模式下的 v2.36)?