是位运算要帮我连载一些布尔变量? [英] Are bitwise operations going to help me to serialize some bools?

查看:142
本文介绍了是位运算要帮我连载一些布尔变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不习惯二进制文件,和我想要得到它的窍门。我设法储存一些整数和无符号的字符,没有太多的痛苦阅读。现在,当我试图节省一些布尔,我看到我的每个布尔的恰恰1个字节在我的文件,因为一个孤独的布尔存储在一个char大小的数据(纠正我,如果我错了,这似乎是合乎逻辑!)。

I'm not used to binary files, and I'm trying to get the hang of it. I managed to store some integers and unsigned char, and read them without too much pain. Now, when I'm trying to save some booleans, I see that each of my bool takes exactly 1 octet in my file, which seems logical since a lone bool is stored in a char-sized data (correct me if I'm wrong!).

但自从我将有3个或4个布尔变量序列化,我想,这就是将它们存储这样的浪费:00000001 00000001 00000000,比如,当我可以有00000110.我想获得这个我应该使用按位运算,但我不是非常好,他们...所以可能有人告诉我:

But since I'm going to have 3 or 4 bools to serialize, I figure it is a waste to store them like this : 00000001 00000001 00000000, for instance, when I could have 00000110. I guess to obtain this I should use bitwise operation, but I'm not very good with them... so could somebody tell me:


  1. 如何使用按位操作存储多达8个的bool在一个字节?

  2. 如何使用位操作给从一个字节正确值(最多8个布尔变量)?

  3. (而且,奖金的问题,没有任何人可以推荐一个简单的,非数学导向的头脑像我这样的,如果存在的位操作教程?一切,我发现我的理解,但不能付诸实践......)

我使用的是C ++,但我想大多数C-syntaxic的语言将使用同一种操作。

I'm using C++ but I guess most C-syntaxic languages will use the same kind of operation.

推荐答案

要存储在一个字节的bool:

To store bools in a byte:

bool flag; // value to store
unsigned char b = 0; // all false
int position; // ranges from 0..7
b = b | (flag << position);

要读回:

flag = (b & (1 << position));

这篇关于是位运算要帮我连载一些布尔变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆