且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何转换__u32在Linux内核__be32

更新时间:2023-11-14 22:38:22

您可以使用kernel.h定义的宏:

http://www.bruceblinn.com/linuxinfo/ByteOrder.html


  

下面的宏返回它已转换后的值。
  注:在linux / kernel.h头文件是头文件,应该是
  包括在其中使用这些宏的源文件,但它是
  不要在那里的宏定义实际的头文件。


块引用>
 的#include<的Linux / kernel.h>
__u16 le16_to_cpu(常量__le16);
__u32 le32_to_cpu(常量__le32);
__u64 le64_to_cpu(常量__le64);__le16 cpu_to_le16(常量__u16);
__le32 cpu_to_le32(常量__u32);
__le64 cpu_to_le64(常量__u64);__u16 be16_to_cpu(常量__be16);
__u32 be32_to_cpu(常量__be32);
__u64 be64_to_cpu(常量__be64);__be16 cpu_to_be16(常量__u16);
__be32 cpu_to_be32(常量__u32);
__be64 cpu_to_be64(常量__u64);

I've a variable

__be32 x;

I've a function

__u32 foo(void){
      __u32 a;
      return a;
}

I need to store the return of foo in variable x.

x=htonl(foo());

Is it correct? I've a confusion that what are the return types of ntohl() and htonl(). Are they opposite of each other?

To check the output, I need to recompile the kernel and I don't want to trouble my system with any errors. So I'm asking here.

You can use the macros defined in kernel.h:

http://www.bruceblinn.com/linuxinfo/ByteOrder.html

The following macros return the value after it has been converted. Note: the linux/kernel.h header file is the header file that should be included in the source files where these macros are used, but it is not the header file where the macros are actually defined.

#include <linux/kernel.h>
__u16   le16_to_cpu(const __le16);
__u32   le32_to_cpu(const __le32);
__u64   le64_to_cpu(const __le64);

__le16  cpu_to_le16(const __u16);
__le32  cpu_to_le32(const __u32);
__le64  cpu_to_le64(const __u64);

__u16   be16_to_cpu(const __be16);
__u32   be32_to_cpu(const __be32);
__u64   be64_to_cpu(const __be64);

__be16  cpu_to_be16(const __u16);
__be32  cpu_to_be32(const __u32);
__be64  cpu_to_be64(const __u64);