简体   繁体   English

如何在 C 中反转 16 位十六进制值?

[英]How to Reverse a 16 bit Hex Value in C?

I'm trying to reverse my value of Pressure data and store this reversed result in the integer uint16_t Pcounts.我正在尝试反转压力数据的值并将此反转结果存储在整数 uint16_t Pcounts 中。 I have found a macro that can be used and it seems to flip some bits but not others.我找到了一个可以使用的宏,它似乎翻转了一些位而不是其他位。 Here is my code:这是我的代码:

#define REV(X) ((X << 24) | (((X>>16)<<24)>>16) | (((X<<16)>>24)<<16) | (X>>24))

uint16_t PressureData;
uint16_t Pcounts;
Pcounts = REV(PressureData);

If PressureData = 0xAABB I would expect Pcounts to be 0xBBAA.如果 PressureData = 0xAABB,我希望 Pcounts 为 0xBBAA。 However, the value comes out to be 0xBB00.但是,该值是 0xBB00。

PressureData is the real-time value of pressure detected from a sensor. PressureData 是从传感器检测到的实时压力值。

If PressureData = 0xAABB I would expect Pcounts to be 0xBBAA.如果 PressureData = 0xAABB,我希望 Pcounts 为 0xBBAA。

Let us assume with abcd , OP wants cdab (byte swap) and not dcba (nibble swap):让我们假设使用abcd ,OP 需要cdab (字节交换)而不是dcba (半字节交换):

The below reverses bytes for a 32-bit value.下面将字节反转为 32 位值。 @Some programmer dude @一些程序员哥们

#define REV(X) ((X << 24) | (((X>>16)<<24)>>16) | (((X<<16)>>24)<<16) | (X>>24))

To reverse bytes for a 16-bit unsigned value.反转 16 位无符号值的字节。 @Eric (Notice () about X .) @Eric (关于X通知() 。)

#define REV16_A(X) (((X) << 8) | ((X)>>8))

Better code would not rely on sign-ness, but force the issue.更好的代码不会依赖符号性,而是强制解决问题。

#define REV16_B(X) (((uint16_t)(X) << 8) | ((uint16_t)(X)>>8))

Yet I see little reason for a macro here and simply use a helper function.然而,我认为这里没有什么理由使用宏,而只是使用辅助函数。 Make it inline if desired.如果需要,使其inline

uint16_t rev16(uint16_t x) {
  return (x << 8) | (x >>8);
}

Further, I expect the desire to flip the bytes is an endian issue.此外,我希望翻转字节的愿望是一个字节序问题。 So if the code is ported, flipping the bytes might / might not be desired.因此,如果移植了代码,则可能/可能不需要翻转字节。 In that case, it is likely the hardware is presenting the bytes in a certain endian which may/may not match the native endian of code.在这种情况下,硬件很可能以特定的字节序呈现字节,该字节序可能/可能不匹配代码的本机字节序。 Consider a helper function to handle that.考虑一个辅助函数来处理这个问题。

uint16_t endian_hw_to_native16(uint16_t x) {
  // endian sensitive code ...
}

The problem is you are overriding some bits.问题是你覆盖了一些位。

Try using a function instead a macro:尝试使用函数而不是宏:

swapped = ((input>>8)&0x0f) | // move byte 1 to byte 0
           (input<<8)&0xf0)); // byte 0 to byte 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM