1bae44755Sopenharmony_ci/*
2bae44755Sopenharmony_ci * Copyright (C) 2022 Huawei Device Co., Ltd.
3bae44755Sopenharmony_ci * Licensed under the Apache License, Version 2.0 (the "License");
4bae44755Sopenharmony_ci * you may not use this file except in compliance with the License.
5bae44755Sopenharmony_ci * You may obtain a copy of the License at
6bae44755Sopenharmony_ci *
7bae44755Sopenharmony_ci *     http://www.apache.org/licenses/LICENSE-2.0
8bae44755Sopenharmony_ci *
9bae44755Sopenharmony_ci * Unless required by applicable law or agreed to in writing, software
10bae44755Sopenharmony_ci * distributed under the License is distributed on an "AS IS" BASIS,
11bae44755Sopenharmony_ci * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12bae44755Sopenharmony_ci * See the License for the specific language governing permissions and
13bae44755Sopenharmony_ci * limitations under the License.
14bae44755Sopenharmony_ci */
15bae44755Sopenharmony_ci
16bae44755Sopenharmony_ci#include <stdbool.h>
17bae44755Sopenharmony_ci#include "endian_internal.h"
18bae44755Sopenharmony_ci
19bae44755Sopenharmony_ci#define B_L_SWAP16(A)  ((((uint16_t)(A) & 0xff00) >> 8) | (((uint16_t)(A) & 0x00ff) << 8))
20bae44755Sopenharmony_ci#define B_L_SWAP32(A)  ((((uint32_t)(A) & 0xff000000) >> 24) | (((uint32_t)(A) & 0x00ff0000) >> 8) | \
21bae44755Sopenharmony_ci    (((uint32_t)(A) & 0x0000ff00) << 8) | (((uint32_t)(A) & 0x000000ff) << 24))
22bae44755Sopenharmony_ci
23bae44755Sopenharmony_cistatic bool CheckEndian(void);
24bae44755Sopenharmony_ci
25bae44755Sopenharmony_cistatic bool CheckEndian(void)
26bae44755Sopenharmony_ci{
27bae44755Sopenharmony_ci    union {
28bae44755Sopenharmony_ci        int32_t i;
29bae44755Sopenharmony_ci        uint8_t s[4];
30bae44755Sopenharmony_ci    } c;
31bae44755Sopenharmony_ci    c.i = 0x12345678;
32bae44755Sopenharmony_ci
33bae44755Sopenharmony_ci    return (c.s[0] == 0x12);
34bae44755Sopenharmony_ci}
35bae44755Sopenharmony_ci
36bae44755Sopenharmony_ciuint32_t HtonlInter(uint32_t h)
37bae44755Sopenharmony_ci{
38bae44755Sopenharmony_ci    return CheckEndian() ? h : B_L_SWAP32(h);
39bae44755Sopenharmony_ci}
40bae44755Sopenharmony_ci
41bae44755Sopenharmony_ciuint32_t NtohlInter(uint32_t n)
42bae44755Sopenharmony_ci{
43bae44755Sopenharmony_ci    return CheckEndian() ? n : B_L_SWAP32(n);
44bae44755Sopenharmony_ci}
45bae44755Sopenharmony_ci
46bae44755Sopenharmony_ciuint16_t HtonsInter(uint16_t h)
47bae44755Sopenharmony_ci{
48bae44755Sopenharmony_ci    return CheckEndian() ? h : B_L_SWAP16(h);
49bae44755Sopenharmony_ci}
50bae44755Sopenharmony_ci
51bae44755Sopenharmony_ciuint16_t NtohsInter(uint16_t n)
52bae44755Sopenharmony_ci{
53bae44755Sopenharmony_ci    return CheckEndian() ? n : B_L_SWAP16(n);
54bae44755Sopenharmony_ci}