1 /* 2 * Copyright (C) 2022 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 #include "endian_internal.h" 17 18 #define B_L_SWAP16(A) ((((uint16_t)(A) & 0xff00) >> 8) | (((uint16_t)(A) & 0x00ff) << 8)) 19 #define B_L_SWAP32(A) ((((uint32_t)(A) & 0xff000000) >> 24) | (((uint32_t)(A) & 0x00ff0000) >> 8) | \ 20 (((uint32_t)(A) & 0x0000ff00) << 8) | (((uint32_t)(A) & 0x000000ff) << 24)) 21 22 int32_t CheckEndian(void); 23 CheckEndian(void)24int32_t CheckEndian(void) 25 { 26 union { 27 int32_t i; 28 uint8_t s[4]; 29 } c; 30 c.i = 0x12345678; 31 32 return (0x12 == c.s[0]); 33 } 34 HtonlInter(uint32_t h)35uint32_t HtonlInter(uint32_t h) 36 { 37 return CheckEndian() ? h : B_L_SWAP32(h); 38 } 39 NtohlInter(uint32_t n)40uint32_t NtohlInter(uint32_t n) 41 { 42 return CheckEndian() ? n : B_L_SWAP32(n); 43 } 44 HtonsInter(uint16_t h)45uint16_t HtonsInter(uint16_t h) 46 { 47 return CheckEndian() ? h : B_L_SWAP16(h); 48 } 49 NtohsInter(uint16_t n)50uint16_t NtohsInter(uint16_t n) 51 { 52 return CheckEndian() ? n : B_L_SWAP16(n); 53 }