2021-01-12 14:29:47 +08:00
|
|
|
## 大端小端扩展函数
|
|
|
|
|
|
|
|
### 1.is\_little
|
2021-01-13 16:05:48 +08:00
|
|
|
|
|
|
|
> 判断当前 CPU 是否是小端。
|
|
|
|
----------------------------
|
|
|
|
|
|
|
|
#### 原型
|
|
|
|
|
|
|
|
```js
|
|
|
|
is_little() => bool
|
|
|
|
```
|
|
|
|
|
2021-01-12 14:29:47 +08:00
|
|
|
### 2.htonl
|
2021-01-13 16:05:48 +08:00
|
|
|
|
|
|
|
> 将类型为 uint32_t 的整数,从主机字节顺序转成网络字节顺序。
|
|
|
|
----------------------------
|
|
|
|
|
|
|
|
#### 原型
|
|
|
|
|
|
|
|
```js
|
|
|
|
htonl(uint32_t) => uint32_t
|
|
|
|
```
|
|
|
|
|
2021-01-12 14:29:47 +08:00
|
|
|
### 3.ntohl
|
2021-01-13 16:05:48 +08:00
|
|
|
> 将类型为 uint32_t 的整数,从网络字节顺序转成主机字节顺序。
|
|
|
|
----------------------------
|
|
|
|
|
|
|
|
#### 原型
|
|
|
|
|
|
|
|
```js
|
|
|
|
ntohl(uint32_t) => uint32_t
|
|
|
|
```
|
|
|
|
|
2021-01-12 14:29:47 +08:00
|
|
|
### 4.htons
|
2021-01-13 16:05:48 +08:00
|
|
|
> 将类型为 uint16_t 的整数,从主机字节顺序转成网络字节顺序。
|
|
|
|
----------------------------
|
|
|
|
|
|
|
|
#### 原型
|
|
|
|
|
|
|
|
```js
|
|
|
|
htons(uint16_t) => uint16_t
|
|
|
|
```
|
|
|
|
|
2021-01-12 14:29:47 +08:00
|
|
|
### 5.ntohs
|
2021-01-13 16:05:48 +08:00
|
|
|
|
|
|
|
> 将类型为 uint16_t 的整数,从网络字节顺序转成主机字节顺序。
|
|
|
|
----------------------------
|
|
|
|
|
|
|
|
#### 原型
|
|
|
|
|
|
|
|
```js
|
|
|
|
ntohs(uint16_t) => uint16_t
|
|
|
|
```
|
|
|
|
|
2021-01-12 14:29:47 +08:00
|
|
|
### 6.htonf
|
2021-01-13 16:05:48 +08:00
|
|
|
|
|
|
|
> 将类型为单精度的浮点数,从主机字节顺序转成网络字节顺序。
|
|
|
|
----------------------------
|
|
|
|
|
|
|
|
#### 原型
|
|
|
|
|
|
|
|
```js
|
|
|
|
htonf(float) => float
|
|
|
|
```
|
|
|
|
|
2021-01-12 14:29:47 +08:00
|
|
|
### 7.ntohf
|
2021-01-13 16:05:48 +08:00
|
|
|
|
|
|
|
> 将类型为单精度的浮点数,从网络字节顺序转成主机字节顺序。
|
|
|
|
----------------------------
|
|
|
|
|
|
|
|
#### 原型
|
|
|
|
|
|
|
|
```js
|
|
|
|
ntohf(float) => float
|
|
|
|
```
|
|
|
|
|
2021-01-12 14:29:47 +08:00
|
|
|
### 8.htonll
|
2021-01-13 16:05:48 +08:00
|
|
|
> 将类型为 uint64_t 的整数,从主机字节顺序转成网络字节顺序。
|
|
|
|
----------------------------
|
|
|
|
|
|
|
|
#### 原型
|
|
|
|
|
|
|
|
```js
|
|
|
|
htonl(uint64_t) => uint64_t
|
|
|
|
```
|
|
|
|
|
2021-01-12 14:29:47 +08:00
|
|
|
### 9.ntohll
|
|
|
|
|
2021-01-13 16:05:48 +08:00
|
|
|
> 将类型为 uint64_t 的整数,从网络字节顺序转成主机字节顺序。
|
|
|
|
----------------------------
|
|
|
|
|
|
|
|
#### 原型
|
|
|
|
|
|
|
|
```js
|
|
|
|
ntohll(uint64_t) => uint64_t
|
|
|
|
```
|
|
|
|
|
2021-01-12 14:29:47 +08:00
|
|
|
### 更多示例
|
|
|
|
|
|
|
|
```js
|
|
|
|
assert(is_little())
|
|
|
|
assert(htonl(0x11223344) == 0x44332211)
|
|
|
|
assert(ntohl(0x11223344) == 0x44332211)
|
|
|
|
assert(htons(0x1122) == 0x2211)
|
|
|
|
assert(ntohs(0x1122) == 0x2211)
|
2021-01-13 16:05:48 +08:00
|
|
|
assert(htonll(0x1122334455667788)==0x8877665544332211)
|
|
|
|
assert(ntohll(0x1122334455667788)==0x8877665544332211)
|
2021-01-12 14:29:47 +08:00
|
|
|
```
|