1 // Protocol Buffers - Google's data interchange format 2 // Copyright 2023 Google LLC. All rights reserved. 3 // 4 // Use of this source code is governed by a BSD-style 5 // license that can be found in the LICENSE file or at 6 // https://developers.google.com/open-source/licenses/bsd 7 8 #ifndef UPB_BASE_INTERNAL_ENDIAN_H_ 9 #define UPB_BASE_INTERNAL_ENDIAN_H_ 10 11 #include <stdint.h> 12 13 // Must be last. 14 #include "upb/port/def.inc" 15 16 #ifdef __cplusplus 17 extern "C" { 18 #endif 19 upb_IsLittleEndian(void)20UPB_INLINE bool upb_IsLittleEndian(void) { 21 const int x = 1; 22 return *(char*)&x == 1; 23 } 24 upb_BigEndian32(uint32_t val)25UPB_INLINE uint32_t upb_BigEndian32(uint32_t val) { 26 if (upb_IsLittleEndian()) return val; 27 28 return ((val & 0xff) << 24) | ((val & 0xff00) << 8) | 29 ((val & 0xff0000) >> 8) | ((val & 0xff000000) >> 24); 30 } 31 upb_BigEndian64(uint64_t val)32UPB_INLINE uint64_t upb_BigEndian64(uint64_t val) { 33 if (upb_IsLittleEndian()) return val; 34 35 const uint64_t hi = ((uint64_t)upb_BigEndian32((uint32_t)val)) << 32; 36 const uint64_t lo = upb_BigEndian32((uint32_t)(val >> 32)); 37 return hi | lo; 38 } 39 40 #ifdef __cplusplus 41 } /* extern "C" */ 42 #endif 43 44 #include "upb/port/undef.inc" 45 46 #endif /* UPB_BASE_INTERNAL_ENDIAN_H_ */ 47