字符串转换为double
- atof
const char *str = "12.3abc";
double value = atof(str);
//value = 12.300000
LOGD("value = %f", value);
const char *str2 = "r12.3abc";
double value2 = atof(str2);
//value = 0.000000
LOGD("value2 = %f", value2);
- strtod:字符串转换为 double 类型,并将非数值类型字符串存储在参数2中
const char *src = "123abc";
char *ptr;
double value = strtod(src, &ptr);
//ptr=abc value= 123.000000
LOGD("value=%lf ptr=%s ", value, ptr);
字符串转换为int
const char *str = "123abc";
int value = atoi(str);
//value = 123
LOGD("value = %d", value);
const char *str2 = "12.9abc";
int value2 = atoi(str2);
//value2 = 12
LOGD("value2 = %d", value2);
字符串转换为long
- atol
const char *str = "123.9F";
long int value = atol(str);
//value = 123
LOGD("test_atol value = %ld", value);
- strtol:根据参数3的进制将字符串转换为 long 类型,并将非数值类型字符串存储在参数2中
const char *src = "123afgh";
char *ptr;
//参数3为识别的进制,可以是任意进制,识别到超出该进制的字符就会停止
long value = strtol(src, &ptr,16);
//ptr=cd value=24755,相当于16进制的 123af
LOGD("test_strtol ptr=%s value=%ld", ptr, value);
内存分配与释放
- malloc:分配内存,但不会初始化为0
- calloc:分配内存,会初始化为0,item_count为分配多少个单元,item_size为每个单元的字节大小
- realloc:重新分配内存大小,原有内存中的内容不变,但是位置可能发生变化(如果数据后面的字节不够,会拷贝到新位置)
- free:释放分配的内存空间
void *buffer = malloc(128);
//buffer addr = 0xb40000798087b580 buffer[0] = -1040187388
LOGD("buffer addr = %p", buffer);
LOGD("buffer[0] = %d", ((int *) buffer)[0]);
void *buffer2 = calloc(128, 1);
//buffer2 addr = 0xb4000079e2062f80 buffer2[0] = 0
LOGD("buffer2 addr = %p", buffer2);
LOGD("buffer2[0] = %d", ((int *) buffer2)[0]);
void *buffer3 = realloc(buffer, 129);
//buffer3 addr = 0xb4000079e2001fa0 buffer3[0] = -1040187388
LOGD("buffer3 addr = %p", buffer3);
LOGD("buffer3[0] = %d", ((int *) buffer3)[0]);
free(buffer2);
free(buffer3);
获取环境变量
char *path = getenv("PATH");
执行 shell 命令
//失败返回-1
int result = system("ls /sdcard/ -l");
伪随机数
伪随机数并不是真正的随机数,它是通过算法生成的固定序列,例如在进程每次重启后,伪随机数的序列是一致的。
int value1 = random();
//生成 0-9 的伪随机数
int value1 = random() % 10;
//设置伪随机数的种子,建议设置为时间戳,可以让伪随机
srand(10);
绝对值
int result = abs(-10);