byte-swap.h

Go to the documentation of this file.
00001 /*
00002 
00003 Copyright (C) 1996-2012 John W. Eaton
00004 
00005 This file is part of Octave.
00006 
00007 Octave is free software; you can redistribute it and/or modify it
00008 under the terms of the GNU General Public License as published by the
00009 Free Software Foundation; either version 3 of the License, or (at your
00010 option) any later version.
00011 
00012 Octave is distributed in the hope that it will be useful, but WITHOUT
00013 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
00014 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
00015 for more details.
00016 
00017 You should have received a copy of the GNU General Public License
00018 along with Octave; see the file COPYING.  If not, see
00019 <http://www.gnu.org/licenses/>.
00020 
00021 */
00022 
00023 #if !defined (octave_byte_swap_h)
00024 #define octave_byte_swap_h 1
00025 
00026 // FIXME -- not sure these volatile qualifiers are really
00027 // needed or appropriate here.
00028 
00029 static inline void
00030 swap_bytes (volatile void *ptr, unsigned int i, unsigned int j)
00031 {
00032   volatile char *t = static_cast<volatile char *> (ptr);
00033 
00034   char tmp = t[i];
00035   t[i] = t[j];
00036   t[j] = tmp;
00037 }
00038 
00039 template <int n>
00040 void
00041 swap_bytes (volatile void *ptr)
00042 {
00043   for (int i = 0; i < n/2; i++)
00044     swap_bytes (ptr, i, n-1-i);
00045 }
00046 
00047 template <>
00048 inline void
00049 swap_bytes <1> (volatile void *)
00050 {
00051 }
00052 
00053 template <>
00054 inline void
00055 swap_bytes <2> (volatile void *ptr)
00056 {
00057   swap_bytes (ptr, 0, 1);
00058 }
00059 
00060 template <>
00061 inline void
00062 swap_bytes <4> (volatile void *ptr)
00063 {
00064   swap_bytes (ptr, 0, 3);
00065   swap_bytes (ptr, 1, 2);
00066 }
00067 
00068 template <>
00069 inline void
00070 swap_bytes <8> (volatile void *ptr)
00071 {
00072   swap_bytes (ptr, 0, 7);
00073   swap_bytes (ptr, 1, 6);
00074   swap_bytes (ptr, 2, 5);
00075   swap_bytes (ptr, 3, 4);
00076 }
00077 
00078 template <int n>
00079 void
00080 swap_bytes (volatile void *ptr, int len)
00081 {
00082   volatile char *t = static_cast<volatile char *> (ptr);
00083 
00084   for (int i = 0; i < len; i++)
00085     {
00086       swap_bytes<n> (t);
00087       t += n;
00088     }
00089 }
00090 
00091 template <>
00092 inline void
00093 swap_bytes<1> (volatile void *, int)
00094 {
00095 }
00096 
00097 #endif
 All Classes Files Functions Variables Typedefs Enumerations Enumerator Friends Defines