BitShifting,将3个u_int8_t存储在一个整数中并再次读出
我有一个问题想问你们,这两天已经让我抓狂了。也许是因为我缺少位移位的基础知识,但不知怎的,我没有把它记在脑子里。我想要的是一个简单的程序,它读取 3 个字符或 uint8_t,将它们存储到一个大 int 中,然后稍后再次将其读出。
这是我第一次尝试位移位,但不知何故我被卡住了。
这是代码:
int main (int argc, const char * argv[])
{
u_int8_t insert1;
u_int8_t insert2;
u_int8_t insert3;
int data;
printf("Please enter value1: ");
scanf("%d", &insert1);
printf("Please enter value2: ");
scanf("%d", &insert2);
printf("Please enter value3: ");
scanf("%d", &insert3);
data |= insert3<<16 | insert2<<8 | insert1;
printf("\nValue1: %d\n", data);
printf("Value2: %d\n", data>>8);
printf("Value3: %d\n", data>>16);
return 0;
}
当我输入
126 时 103 255
我得到:
值1:16711680 值2:65280 Value3: 255
这是完全错误的。我很确定该值已正确存储到数据中,但我不知道如何读出。
非常感谢:-)
i have a question for you guys which is driving me nuts for 2 days already. Maybe its because i am missing the basics on bit shifting but somehow i don't get it into my head. What i want is a simple program which reads in 3 char or uint8_t's, stores them into one big int and then reads it out later again.
It is the first time that i experiment with bit shifting, and somehow i am stuck.
This is the code:
int main (int argc, const char * argv[])
{
u_int8_t insert1;
u_int8_t insert2;
u_int8_t insert3;
int data;
printf("Please enter value1: ");
scanf("%d", &insert1);
printf("Please enter value2: ");
scanf("%d", &insert2);
printf("Please enter value3: ");
scanf("%d", &insert3);
data |= insert3<<16 | insert2<<8 | insert1;
printf("\nValue1: %d\n", data);
printf("Value2: %d\n", data>>8);
printf("Value3: %d\n", data>>16);
return 0;
}
When i Enter
126
103
255
i get:
Value1: 16711680
Value2: 65280
Value3: 255
Which is completely wrong. I am pretty sure that the value is stored correctly stored into data but i don't know how to read out.
Thanks very much :-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
发布评论
评论(3)
您遇到三个错误:
您将指向
uint8_t
的指针传递给scanf
,但您正在使用%d
转换它需要一个指向int
的指针;您需要使用%hhd
告诉scanf
您正在使用char
大小的存储,否则您将面临损坏堆栈的风险;或者您可以将变量更改为int
类型,或者更好(因为问题被标记为C++
)使用std::istream
提取类型安全的运算符 (operator >>
)您没有初始化
data
,而是使用了|=
,因此将未初始化的值与用户输入的值混合在一起(这将产生垃圾)- < p>使用
printf
时,如果只想看到低位,则需要屏蔽高位
所以,您的需要阅读的代码:
#include <iostream>
static void readvalue(const char* name, uint8_t& outValue) {
std::cout << "Please enter " << name << ": " << std::flush;
std::cin >> outValue;
std::cout << "\n";
}
int main() {
uint8_t value1, value2, value3;
readvalue("value1", value1);
readvalue("value2", value2);
readvalue("value3", value3);
data = insert3<<16 | insert2<<8 | insert1;
std::cout << "Value1: " << (data & 0xff);
std::cout << "Value2: " << ((data >> 8) & 0xff);
std::cout << "Value3: " << ((data >> 16) & 0xff);
}
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
您从未初始化过
data
并且您正在执行以下操作:将其初始化为零或将行更改为:
You never initialized
data
and you're doing this:Either initialize it to zero or change the line to this: