I need to write a function to convert big endian to little endian in C. I can not use any library function.
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
By including:
you can get an optimized version of machine-dependent byte-swapping functions. Then, you can easily use the following functions:
or
Here's a fairly generic version; I haven't compiled it, so there are probably typos, but you should get the idea,
NB: This is not optimised for speed or space. It is intended to be clear (easy to debug) and portable.
Update 2018-04-04 Added the assert() to trap the invalid case of n == 0, as spotted by commenter @chux.
As a joke:
here's a way using the SSSE3 instruction pshufb using its Intel intrinsic, assuming you have a multiple of 4
int
s:Here's a function I have been using - tested and works on any basic data type:
Update : Added 64bit byte swapping