“3bed29dddad59921d66e264c3d6ba9981ec6b3b0”上不存在“decoders/git@gitcode.net:paddlepaddle/DeepSpeech.git”
提交 99cbca6f 编写于 作者: F feilong

add hex

上级 d0d8f063
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void bin_to_hex(const void *data, uint32_t len, char *out) {
static const char *const lut = "0123456789abcdef";
uint32_t i;
for (i = 0; i < len; ++i) {
uint8_t c = ((uint8_t *)data)[i];
out[i * 2] = lut[c >> 4];
out[i * 2 + 1] = lut[c & 15];
}
}
int main(int argc, char **argv) {
char *str = "HelloWorld!";
char *hex = (char *)malloc(512 * sizeof(char));
bin_to_hex(str, strlen(str), hex);
printf("%s", hex);
return 0;
}
\ No newline at end of file
{
"type": "code_options",
"author": "幻灰龙",
"source": "bin_to_hex.md"
}
\ No newline at end of file
# 十六进制转换
将任意二进制数据转成16进制并打印hex字符串
## template
```c
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
$code
int main(int argc, char **argv) {
char *str = "HelloWorld!";
char *hex = (char *)malloc(512 * sizeof(char));
bin_to_hex(str, strlen(str), hex);
printf("%s", hex);
return 0;
}
```
## 答案
```c
void bin_to_hex(const void *data, uint32_t len, char *out) {
static const char *const lut = "0123456789abcdef";
uint32_t i;
for (i = 0; i < len; ++i) {
uint8_t c = ((uint8_t *)data)[i];
out[i * 2] = lut[c >> 4];
out[i * 2 + 1] = lut[c & 15];
}
}
```
## 选项
### 选项1
```c
void bin_to_hex(const void *data, uint32_t len, char *out) {
static const char *const lut = "0123456789abcdef";
uint32_t i;
for (i = 0; i < len; ++i) {
uint8_t c = ((uint8_t *)data)[i];
out[i * 2] = lut[c >> 4];
out[i * 2 + 1] = lut[c << 4];
}
}
```
### 选项2
```c
void bin_to_hex(const void *data, uint32_t len, char *out) {
static const char *const lut = "0123456789abcdef";
uint32_t i;
for (i = 0; i < len; ++i) {
uint8_t c = ((uint8_t *)data)[i];
out[i * 2] = lut[c << 4];
out[i * 2 + 1] = lut[c & 15];
}
}
```
### 选项3
```c
void bin_to_hex(const void *data, uint32_t len, char *out) {
static const char *const lut = "0123456789abcdef";
uint32_t i;
for (i = 0; i < len; ++i) {
uint8_t c = ((uint8_t *)data)[i];
out[i * 2] = lut[c >> 4];
out[i * 2 + 1] = lut[c & 16];
}
}
```
\ No newline at end of file
......@@ -6,5 +6,7 @@
"C语言"
],
"children": [],
"export": []
"export": [
"bin_to_hex.json"
]
}
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册