byte order – Linux kernel byte order APIs

Most of the time, user-space applications do not care about the endian of the running machine, like we call send() and recv() directly expecting the right order of the data and they work! However, things could be changed if you are dealing with low-level data processing in the kernel space, such as file systems and device drivers. The good thing is the kernel has provided a standard set of APIs which are used to do byte order conversion. In this post, we implement a kernel module playing with these APIs – trying to help understand the usage and effect of these APIs. Have fun~

0. APIs

le16(/32/64)_to_cpu
cpu_to_le16(/32/64)
be16(/32/64)_to_cpu
cpu_to_be16(/32/64)

1. x86_64 arch

global_data:
01 23 45 67 89 ab cd ef
le16_to_cpu:
01 23 45 67 89 ab cd ef
le32_to_cpu:
01 23 45 67 89 ab cd ef
le64_to_cpu:
01 23 45 67 89 ab cd ef
cpu_to_le16:
01 23 45 67 89 ab cd ef
cpu_to_le32:
01 23 45 67 89 ab cd ef
cpu_to_le64:
01 23 45 67 89 ab cd ef
be16_to_cpu:
23 01 67 45 ab 89 ef cd
be32_to_cpu:
67 45 23 01 ef cd ab 89
be64_to_cpu:
ef cd ab 89 67 45 23 01
cpu_to_be16:
23 01 67 45 ab 89 ef cd
cpu_to_be32:
67 45 23 01 ef cd ab 89
cpu_to_be64:
ef cd ab 89 67 45 23 01

2. Note

Though there is a standard set of byte order APIs, they are architecture dependent. For example, ARM arch may share the same results as x86_64 while Power/SPARC may have different ones. The rule of thumb here is – Do NOT create your own byte order APIs; Stick with these standard kernel APIs!

3. R.t.D.C.

https://github.com/daveti/kbo

About daveti

Interested in kernel hacking, compilers, machine learning and guitars.
This entry was posted in OS, Programming and tagged , , . Bookmark the permalink.

2 Responses to byte order – Linux kernel byte order APIs

  1. 看不懂看不懂。哈哈

  2. 94Fallon says:

    Hello blogger, i must say you have hi quality
    articles here. Your website should go viral.
    You need initial traffic only. How to get it? Search for; Mertiso’s tips go viral

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s