1 /* 2 * Copyright (c) 2021 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef ENDIAN_CONVERT_H 17 #define ENDIAN_CONVERT_H 18 19 #include <cstddef> 20 #include <cstdint> 21 22 namespace DistributedDB { IsBigEndian()23inline bool IsBigEndian() 24 { 25 uint32_t data = 0x12345678; // 0x12345678 only used here, for endian test 26 uint8_t *firstByte = reinterpret_cast<uint8_t *>(&data); 27 if (*firstByte == 0x12) { // 0x12 only used here, for endian test 28 return true; 29 } 30 return false; 31 } 32 HostToNet(const T & from)33template<typename T> T HostToNet(const T &from) 34 { 35 if (IsBigEndian()) { 36 return from; 37 } else { 38 T to; 39 size_t typeLen = sizeof(T); 40 const uint8_t *fromByte = reinterpret_cast<const uint8_t *>(&from); 41 uint8_t *toByte = reinterpret_cast<uint8_t *>(&to); 42 for (size_t i = 0; i < typeLen; i++) { 43 toByte[i] = fromByte[typeLen - i - 1]; // 1 is for index boundary 44 } 45 return to; 46 } 47 } 48 NetToHost(const T & from)49template<typename T> T NetToHost(const T &from) 50 { 51 return HostToNet(from); 52 } 53 } 54 55 #endif