字节序判断
iOS中的字节序转换和字节序判断方法详见 NSByteOrder.h 文件中, 具体实现见 CFByteOrder.h
// - 0x01020304在内存中的表现, 小字节序 : 04 03 02 01, 大字节序 01 02 03 04 iOS系统是小字节序;
static uint8_t is_little_endian(){
union {
int a;
uint8_t b;
}c;
// - 此时共用体 c在iOS系统内存中的表现是 01 00 00 00; 则 c.a = 0x00000001, c.b = 0x01, c.a == c.b, 表示了iOS系统是小字节序;
c.a = 1;
return c.b == 1;
/** 地址 低->高 */
c.a = 0x01020304;
0x7ffeefbff388 : 04 03 02 01
c.b = 0x05;
0x7ffeefbff388 : 05 03 02 01
struct {
int a;
int b;
}c;
c.a = 0x01020304;
c.b = 0x05060708;
/** 地址 低->高 */
0x7ffeefbff388 : 04 03 02 01 08 07 06 05
}
数据读写功能的实现
/* 可以用于二进制数据的持续读写 */
#ifndef aw_data_h
#define aw_data_h
#include <stdio.h>
// - 定义数据读写的结构体
//文件数据
typedef struct aw_data{
uint32_t size;//有效数据长度
uint32_t alloc_size;//分配的数据长度
uint32_t curr_pos;//读取或写入的位置
uint8_t *data;//实际数据
}aw_data;
//数据读取,自动处理大小端
typedef struct aw_data_reader{
uint8_t (*read_uint8)(aw_data *); // - 读取1个字节
uint16_t (*read_uint16)(aw_data *); // - 读取2个字节
uint32_t (*read_uint24)(aw_data *); // - 读取3个字节
uint32_t (*read_uint32)(aw_data *); // - 读取4个字节
uint64_t (*read_uint64)(aw_data *); // - 读取8个字节
double (*read_double)(aw_data *); // - 读取double类型
void (*read_string)(aw_data *, char **, int); // - 读取指定长度的字符串
void (*read_bytes)(aw_data *, char **, int); // - 读取指定长度的字节
void (*skip_bytes)(aw_data *, int); // - 跳过指定长度的字节
int (*remain_count)(aw_data *); // - 获取剩余没有读取的字节的长度
//debug,纪录某个程序段,一共读取数据的数量。
void (*start_record_size)();
size_t (*record_size)();
void (*end_record_size)();
void (*start_read)(aw_data *);
}aw_data_reader;
//数据写入,自动处理大小端
typedef struct aw_data_writer{
void (*write_uint8)(aw_data **, uint8_t); // - 写入1个字节
void (*write_uint16)(aw_data **, uint16_t); // - 写入2个字节
void (*write_uint24)(aw_data **, uint32_t); // - 写入3个字节
void (*write_uint32)(aw_data **, uint32_t); // - 写入4个字节
void (*write_uint64)(aw_data **, uint64_t); // - 写入8个字节
void (*write_double)(aw_data **, double); // - 写入double
void (*write_string)(aw_data **, const char *, uint32_t); // - 写入指定长度的字符串,并且将字符长度写在字符串前 uint32_t 字节中;
void (*write_bytes)(aw_data **, const uint8_t *, uint32_t); // - 写入指定长度的字节
void (*write_empty_bytes)(aw_data **, uint32_t); // - 写入空字节
//debug,纪录某个程序段,一共写入数据的数量。
void (*start_record_size)();
size_t (*record_size)();
void (*end_record_size)();
}aw_data_writer;
//全局读写 reader 和 writer
extern aw_data_reader data_reader;
extern aw_data_writer data_writer;
#include "aw_data.h"
#include <string.h>
#include <stdlib.h>
static int8_t aw_is_started_record_size = 0;
static uint32_t aw_recorded_size = 0;
static void aw_start_record_size(){
if (aw_is_started_reco