changeset 453:30086c1aca30

endianness
author Sebastien Jodogne <s.jodogne@gmail.com>
date Thu, 04 Jul 2013 14:29:44 +0200
parents 80f7539147a2
children 6f47a4262618
files Core/Enumerations.h Core/PngWriter.cpp Core/Toolbox.cpp Core/Toolbox.h UnitTests/main.cpp
diffstat 5 files changed, 47 insertions(+), 2 deletions(-) [+]
line wrap: on
line diff
--- a/Core/Enumerations.h	Thu Jul 04 11:48:02 2013 +0200
+++ b/Core/Enumerations.h	Thu Jul 04 14:29:44 2013 +0200
@@ -36,6 +36,13 @@
 
 namespace Orthanc
 {
+  enum Endianness
+  {
+    Endianness_Unknown,
+    Endianness_Big,
+    Endianness_Little
+  };
+
   enum ErrorCode
   {
     // Generic error codes
--- a/Core/PngWriter.cpp	Thu Jul 04 11:48:02 2013 +0200
+++ b/Core/PngWriter.cpp	Thu Jul 04 14:29:44 2013 +0200
@@ -37,6 +37,7 @@
 #include <png.h>
 #include "OrthancException.h"
 #include "ChunkedBuffer.h"
+#include "Toolbox.h"
 
 
 // http://www.libpng.org/pub/png/libpng-1.2.5-manual.html#section-4
@@ -171,9 +172,14 @@
       switch (format)
       {
       case PixelFormat_Grayscale16:
-        // Must swap the endianness!!
         png_set_rows(pimpl_->png_, pimpl_->info_, &pimpl_->rows_[0]);
-        png_write_png(pimpl_->png_, pimpl_->info_, PNG_TRANSFORM_SWAP_ENDIAN, NULL);
+
+        if (Toolbox::DetectEndianness() == Endianness_Little)
+        {
+          // Must swap the endianness!!
+          png_write_png(pimpl_->png_, pimpl_->info_, PNG_TRANSFORM_SWAP_ENDIAN, NULL);
+        }
+
         break;
 
       default:
--- a/Core/Toolbox.cpp	Thu Jul 04 11:48:02 2013 +0200
+++ b/Core/Toolbox.cpp	Thu Jul 04 14:29:44 2013 +0200
@@ -34,6 +34,7 @@
 
 #include "OrthancException.h"
 
+#include <stdint.h>
 #include <string.h>
 #include <boost/filesystem.hpp>
 #include <boost/filesystem/fstream.hpp>
@@ -671,4 +672,29 @@
 
     s.resize(target);
   }
+
+
+  Endianness Toolbox::DetectEndianness()
+  {
+    // http://sourceforge.net/p/predef/wiki/Endianness/
+
+    uint8_t buffer[4];
+
+    buffer[0] = 0x00;
+    buffer[1] = 0x01;
+    buffer[2] = 0x02;
+    buffer[3] = 0x03;
+
+    switch (*((uint32_t *)buffer)) 
+    {
+      case 0x00010203: 
+        return Endianness_Big;
+
+      case 0x03020100: 
+        return Endianness_Little;
+        
+      default:
+        throw OrthancException(ErrorCode_NotImplemented);
+    }
+  }
 }
--- a/Core/Toolbox.h	Thu Jul 04 11:48:02 2013 +0200
+++ b/Core/Toolbox.h	Thu Jul 04 14:29:44 2013 +0200
@@ -32,6 +32,8 @@
 
 #pragma once
 
+#include "Enumerations.h"
+
 #include <stdint.h>
 #include <vector>
 #include <string>
@@ -101,5 +103,7 @@
 
     // In-place percent-decoding for URL
     void UrlDecode(std::string& s);
+
+    Endianness DetectEndianness();
   }
 }
--- a/UnitTests/main.cpp	Thu Jul 04 11:48:02 2013 +0200
+++ b/UnitTests/main.cpp	Thu Jul 04 14:29:44 2013 +0200
@@ -461,6 +461,8 @@
   // Go to trace-level verbosity
   //FLAGS_v = 1;
 
+  Toolbox::DetectEndianness();
+
   google::InitGoogleLogging("Orthanc");
 
   OrthancInitialize();