SSP21-CPP
FloatByteOrder.h
1 /*
2  * Copyright (c) 2018, Automatak LLC
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
6  * following conditions are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
9  * disclaimer.
10  *
11  * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
12  * disclaimer in the documentation and/or other materials provided with the distribution.
13  *
14  * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
15  * products derived from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
18  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19  * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
21  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
22  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
23  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25 #ifndef SER4CPP_FLOAT_BYTE_ORDER_H
26 #define SER4CPP_FLOAT_BYTE_ORDER_H
27 
28 #include "ser4cpp/util/Uncopyable.h"
29 
30 #include <cstdint>
31 
32 namespace ser4cpp
33 {
34 
35 struct FloatByteOrder : private StaticOnly
36 {
37 public:
38  enum class Value : uint8_t
39  {
40  normal,
41  reverse,
42  unsupported
43  };
44 
45  static Value order()
46  {
47  static Value order = get_byte_order();
48  return order;
49  }
50 
51 private:
52  union FloatUnion
53  {
54  uint8_t bytes[4];
55  float f;
56  };
57 
58  static Value get_byte_order()
59  {
60  if (is_normal_byte_order())
61  {
62  return FloatByteOrder::Value::normal;
63  }
64  else if (is_reverse_byte_order())
65  {
66  return FloatByteOrder::Value::reverse;
67  }
68  else
69  {
70  return FloatByteOrder::Value::unsupported;
71  }
72  }
73 
74  static bool is_normal_byte_order()
75  {
76  FloatUnion value = {{ 0x00, 0x00, 0xA0, 0xC1 }};
77  return (value.f == -20.0f);
78  }
79 
80  static bool is_reverse_byte_order()
81  {
82  FloatUnion value = {{ 0xC1, 0xA0, 0x00, 0x00 }};
83  return (value.f == -20.0f);
84  }
85 };
86 
87 }
88 
89 #endif
ser4cpp header-only library namespace
Definition: Buffer.h:33