C-language Linux kernel implementation of high and low level swap

Source: Internet
Author: User

Linux kernel is really profound, there are a lot of excellent algorithms, I have encountered in the work of the high-low level exchange problem, at that time for C language is not very skilled, think for a long period to write out. Recently, when looking at the kernel, I saw a kernel engineer implement this algorithm, as I thought before, then share it today.

In the development requirements, there are 32-bit, 16-bit, 8-bit high-low-level switching algorithms. So let's look at the code implementation in detail:

Also, pull the code out of the Linux kernel:

#include <stdio.h>//a 8-digit high-low 4-bit exchange static inline unsigned char bswap_8 (unsigned char v) {return ((V & 0xff) <&lt ; 4) |   (v >> 4); The parameters (V & 0xff) << 4 equal to the high position, v >> 4 bits equal to the low level}//The following two code analysis is identical/ /Convert a 16-bit high-low 8-bit to static inline unsigned short bswap_16 (unsigned short v) {return ((V & 0xff) << 8) | (v >> 8);} Swap a 32-bit high-low 16-bit for static inline unsigned int bswap_32 (unsigned int v) {return ((V & 0xff) << 24) | ((V & 0xff00) << 8) | ((V & 0xff0000) >> 8) | (v >> 24);} int main (void) {unsigned short v = 0x1000;p rintf ("1, \ n Original v:%d\n", V);p rintf ("16-digit high-low 8-bit converted v:%d (0x%x) =========>0x% X--->%d\n ", v,v, Bswap_16 (v), Bswap_16 (v)), unsigned char a = 0x0a;p rintf (" \n2, \ n Original a:%d\n ", a);p rintf (" 8-digit high-low 4-bit converted A :%d (0x%x) ==========>0x%x--->%d\n ", a,a, Bswap_8 (a), Bswap_8 (a)); unsigned int b = 0x00001111; printf ("\n3, \ n Original b:%d\n", b);p rintf ("32-digit 16-bit conversion b:%d (0x%x) ========>0x%x--->%d\N ", B,b, bswap_32 (b), bswap_32 (b)); return 0;} 
Operation Result:

From the running results, three interfaces have realized the exchange of data high and low level, and verified the success!



C-language Linux kernel implementation of high and low level swap

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.