平常看的一些开源代码,遇到了一些黑科技。在总结一下
1、将数字压缩写入字符串中
比如int的最大值是2^31次方,好多位阿,我想写在string中,岂不是要这样写?潜意识都会这么写的,那么我们有什么办法只写在前四个字节中吗?当然有了。
string s;
s = to_string(INT_MAX);
用下面的代码,可以清晰看到,把值写到s2的比特位中了,只占用了4个字节.取出他的地址在强转程char*。
int num = INT32_MAX; // windows下INT_MAX也可以
string s2((char*)&num,4);
cout << s2.size() << endl;
int ans = 0;
s2.copy((char*)&ans,4,0);
cout << ans << endl;
2、当函数只能接受int32的参数的时候,但我想传int64的值怎么办?
把64位的变量拆分为两个。云风的协程库对写法。ptr作为低32位。ptr>>32做为高32位的。
uintptr_t ptr = (uintptr_t)sdu.get();// sdu是个智能指针。
makecontext(&co->ctx,(void (*)(void))&Fiber::mainfunc,2,
(uint32_t)ptr, (uint32_t)(ptr>>32));
如何合并呢?将每一位的bit进行一个与操作即可
void Fiber::mainfunc(uint32_t low32, uint32_t hi32) {
uintptr_t ptr = (uintptr_t)low32 | ((uintptr_t)hi32 << 32);
struct schedule* sdu = (struct schedule *)ptr;
}
3、利用栈空间
int main(){
char* stack = (char*)malloc(20);
char ptr[20]= "hello world";
char* top = ptr + 20;
char dummy = 0;
int size = top - &dummy;
memcpy(stack,&dummy + 1,size -1);
cout << "dummy 地址 " << (long)&dummy << endl;
cout << "栈底 地址 " << (long)&ptr[0] << endl;
cout << "栈顶 地址 " << (long)&ptr[19] << endl;
cout << "指针值 " << stack << endl;
free(stack);
return 0;
}
你猜猜stack值是多什么?没想到把,就是hello world
dummy相当于是栈顶。他的上一个位值就是ptr[0],所以可以这么写