3

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.

RatDon
  • 3,403
  • 8
  • 43
  • 85

1 Answers1

8

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);
Nick
  • 25,026
  • 7
  • 51
  • 83
  • 3
    ... and the macro to actually use here would be `x = cpu_to_be32(foo());`. – unwind Feb 21 '14 at 11:25
  • @unwind Thanks. But the aliases are easy to use. – RatDon Feb 21 '14 at 11:30
  • @Nick Why so stubborn man. Why are you discarding my edit. I'm asking about `ntohl()` and `htonl()`. The link you provided mentioned them. I've got my answer and aliases are better than the actual macros. so I'm editing to include the aliases. – RatDon Feb 21 '14 at 11:45
  • What's that? I was away... didn't discard anything. Put them back in and I'll approve... Or them as a different answer. – Nick Feb 21 '14 at 11:53
  • @Nick Don't know. At a moment I'm able to see my edit with "waiting for peer review". And the next moment, It's gone. – RatDon Feb 21 '14 at 11:55
  • It got rejected by the review queue. Anyway - the htonl/ntohl macros are more specific to networking rather than general bit endianness. They're read as HostToNetworkLong and NetworkToHostLong. – Nick Feb 21 '14 at 11:57
  • 1
    Link is broken and I couldn't find a replacement ): – vmemmap Jun 13 '22 at 11:32
  • @Roi link still working for me. Maybe the site was down temporarily. – Nick Jun 27 '22 at 12:14
  • @Nick Oh! It really _is_ working now. – vmemmap Jun 27 '22 at 13:16