1 /*
2  * Copyright (c) 2024 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 #define LOG_TAG "EndianConverter"
16 #include "endian_converter.h"
17 
18 #include "error_code.h"
19 #include "logger.h"
20 #include "securec.h"
21 
22 namespace OHOS {
23 namespace UDMF {
HostToNet(float value)24 float HostToNet(float value)
25 {
26     uint32_t temp;
27     auto err = memcpy_s(&temp, sizeof(temp), &value, sizeof(temp));
28     if (err != E_OK) {
29         LOG_ERROR(UDMF_KITS_NAPI, "memcpy_s error: %{public}d", err);
30     }
31     temp = htole32(temp);
32     err = memcpy_s(&value, sizeof(value), &temp, sizeof(value));
33     if (err != E_OK) {
34         LOG_ERROR(UDMF_KITS_NAPI, "memcpy_s error: %{public}d", err);
35     }
36     return value;
37 }
38 
NetToHost(float value)39 float NetToHost(float value)
40 {
41     uint32_t temp;
42     auto err = memcpy_s(&temp, sizeof(temp), &value, sizeof(temp));
43     if (err != E_OK) {
44         LOG_ERROR(UDMF_KITS_NAPI, "memcpy_s error: %{public}d", err);
45     }
46     temp = le32toh(temp);
47     err = memcpy_s(&value, sizeof(value), &temp, sizeof(value));
48     if (err != E_OK) {
49         LOG_ERROR(UDMF_KITS_NAPI, "memcpy_s error: %{public}d", err);
50     }
51     return value;
52 }
53 
HostToNet(double value)54 double HostToNet(double value)
55 {
56     uint64_t temp;
57     auto err = memcpy_s(&temp, sizeof(temp), &value, sizeof(temp));
58     if (err != E_OK) {
59         LOG_ERROR(UDMF_KITS_NAPI, "memcpy_s error: %{public}d", err);
60     }
61     temp = htole64(temp);
62     err = memcpy_s(&value, sizeof(value), &temp, sizeof(value));
63     if (err != E_OK) {
64         LOG_ERROR(UDMF_KITS_NAPI, "memcpy_s error: %{public}d", err);
65     }
66     return value;
67 }
68 
NetToHost(double value)69 double NetToHost(double value)
70 {
71     uint64_t temp;
72     auto err = memcpy_s(&temp, sizeof(temp), &value, sizeof(temp));
73     if (err != E_OK) {
74         LOG_ERROR(UDMF_KITS_NAPI, "memcpy_s error: %{public}d", err);
75     }
76     temp = le64toh(temp);
77     err = memcpy_s(&value, sizeof(value), &temp, sizeof(value));
78     if (err != E_OK) {
79         LOG_ERROR(UDMF_KITS_NAPI, "memcpy_s error: %{public}d", err);
80     }
81     return value;
82 }
83 } // namespace UDMF
84 } // namespace OHOS