1> How do I determine whether the CPU of a Board is big-Endian or little-Endian?
It is very easy to implement in C. After about 10 lines, we can determine whether new users know what is the difference between endian and big-Endian and little-Endian, if these are unclear, even if C is strong, it cannot be suppressed.
2> after judging how to convert the endian, write two functions.
If we say the above one, we may not be able to correctly evaluate the C level of the new person. The following figure shows the result.
In particular, write a macro for implementation. I think macros can best reflect a person's level. We all know that they are powerful, but they are written again.
A very simple macro is hard to write. Pay special attention to type conversion and big expansion. Writing a function is much easier.
You can implement it, use a macro, or use a function. It is best to give it a try.
The main focus is on the use of macros.
For example:
Function Format:
Typedef unsigned int u32;
Typedef unsigned short 2010;
Bswap16 );
U32 bswap32 (u32 );
Written into a macro:
# Define bswap_16 (X)
....
# Define bswap_32 (X)
....
For example: 0x1234 to: 0x3412
Or: 0x12345678 to: 0x78563412
---
The reply below is a bit messy. Let's just tie it out here. The format is better:
1. It is very easy to judge the endian problem.
Determine endian:
# Include <stdio. h>
# Include <stdlib. h>
Int main (void)
{
Short int A = 0x1234;
Char * P = (char *) &;
Printf ("P = % # hhx \ n", * P );
If (* P = 0x34)
Printf ("little endian \ n ");
Else if (* P = 0x12)
Printf ("Big endian \ n ");
Else
Printf ("unknow endian \ n ");
Return 0;
}
2> how to convert:
# Include <stdio. h>
# Include <stdio. h>
Typedef unsigned int u32;
Typedef unsigned short 2010;
# If 0
// Simple: not check Varible types
# Define bswap_16 (x )\
(X) & 0x00ff) <8) | \
(X) & 0xff00)> 8 )\
)
// Complex: Check Varible types
# Else
# Define bswap_16 (x )\
() (X) & 0x00ff) <8) | \
() (X) & 0xff00)> 8 )\
)
# Endif
# Define bswap_32 (x )\
(U32) (u32) (x) & 0xff000000)> 24) | \
(U32) (x) & 0x00ff0000)> 8) | \
(U32) (x) & 0x0000ff00) <8) | \
(U32) (x) & 0x000000ff) <24 )\
)
162bswap16 (162xx)
{
Return (X & 0x00ff) <8 |
(X & 0xff00)> 8
;
}
U32 bswap32 (u32 X)
{
Return (X & 0xff000000)> 24 |
(X & 0x00ff0000)> 8 |
(X & 0x0000ff00) <8 |
(X & 0x000000ff) <24
;
}
Int main (void)
{
// 2010var_short = 0x123490;
// U32 var_int = 0x1234567890;
// The key is to be able to handle the error. If 0x123490 is given, the 0x9034 value can still be obtained, and the memory size is small.
Printf ("macro conversion: % # x \ n", bswap_16 (0x123490); // Correct Conversion
Printf ("macro conversion: % # x \ n", bswap_32 (0x1234567890); // Correct Conversion
Printf ("----------------- \ n ");
Printf ("Function Conversion: % # x \ n", bswap16 (0x123490 ));
Printf ("Function Conversion: % # x \ n", bswap32 (0x1234567890 ));
Return 0;
}