1 /* Copyright (c) 2000 Alexandre Oliva <aoliva@redhat.com> */
2 /*
3 FUNCTION
4 	<<swab>>---swap adjacent bytes
5 
6 SYNOPSIS
7 	#include <unistd.h>
8 	void swab(const void *<[in]>, void *<[out]>, ssize_t <[n]>);
9 
10 DESCRIPTION
11 	This function copies <[n]> bytes from the memory region
12 	pointed to by <[in]> to the memory region pointed to by
13 	<[out]>, exchanging adjacent even and odd bytes.
14 
15 PORTABILITY
16 <<swab>> requires no supporting OS subroutines.
17 */
18 
19 #define _XOPEN_SOURCE
20 #include <unistd.h>
21 
22 void
swab(const void * b1,void * b2,ssize_t length)23 swab (const void *b1,
24 	void *b2,
25 	ssize_t length)
26 {
27   const char *from = b1;
28   char *to = b2;
29   ssize_t ptr;
30   for (ptr = 1; ptr < length; ptr += 2)
31     {
32       char p = from[ptr];
33       char q = from[ptr-1];
34       to[ptr-1] = p;
35       to[ptr  ] = q;
36     }
37   if (ptr == length) /* I.e., if length is odd, */
38     to[ptr-1] = 0;   /* then pad with a NUL. */
39 }
40