#include <stdio.h>
#include <stdint.h>
void itobytes(int n, unsigned char *bytes)
{
// 64位系统中一个int占4个字节
*bytes++ = (n >> 24) & 0xFF;
*bytes++ = (n >> 16) & 0xFF;
*bytes++ = (n >> 8) & 0xFF;
*bytes++ = n & 0xFF;
}
// printf的时候,加上统一的前缀
#define PREFIX "WW:"
#define SLSTD "%s:%d"
void print_int(int n)
{
unsigned char data[4];
itobytes(n, data);
printf(SLSTD "%d ", __func__, __LINE__, n);
const char* title = "bytes";
int length = 4;
int i;
fprintf(stderr, GREEN_COLOR PREFIX "%s: ", title);
for (i = 0; i < length; ++i) {
fprintf(stderr, "%02x ", data[i]);
if (((i + 1) % 32) == 0)
fprintf(stderr, "\n");
}
fprintf(stderr, "\n" GREEN_COLOR);
}
c:int转bytes,打印输出printf
于 2023-03-01 11:57:23 首次发布
该代码示例展示了如何在C语言中将整数`n`转换为字节数组,并以十六进制格式打印。函数`itobytes`将整数拆分为字节,`print_int`则使用`printf`和`fprintf`进行格式化输出,包括函数名、行号和字节的十六进制表示。
337

被折叠的 条评论
为什么被折叠?



