简体   繁体   English

从文件中读取十六进制数

[英]Reading in HEX number from file

This has me pretty bothered as I should be able to do it but when I read in the hex number and assign it to an unsigned int when I print it out I get a different number.这让我很困扰,因为我应该能够做到,但是当我读入十六进制数字并将其分配给无符号整数时,当我打印出来时,我得到一个不同的数字。 Any advice would be great.任何建议都会很棒。 Thanks谢谢

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
fstream myfile;
myfile.open("test.text");
unsigned int tester;
string test;
myfile >> hex >> tester;
cout << tester;
system("pause");
return 0;
}

I bet you don't get a "different number".我敢打赌,您不会得到“不同的号码”。

I bet you get the same value, but in decimal representation.我敢打赌,您会得到相同的值,但以十进制表示。

You're already extracting a hex-representation value ( myfile >> hex >> tester );您已经在提取一个十六进制表示值( myfile >> hex >> tester ); now insert one, too ( cout << hex << tester )!现在也插入一个( cout << hex << tester )!

This works for hex value in string format to int这适用于字符串格式的十六进制值到 int

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
    fstream myfile;
    myfile.open("test.txt");
    string fromFile;
    unsigned int tester;

    myfile >> fromFile;
    istringstream iss(fromFile);
    iss >> hex >> tester;
    cout << tester;

    system("pause");
    return 0;
}

This works int to hex这适用于十六进制

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
fstream myfile;
myfile.open("test.txt");
unsigned int tester;
string test;
myfile >> tester;
cout << hex << tester;

system("pause");
return 0;
}

Also check your filename.还要检查您的文件名。 In my file It had a 54 written on it than output was 36 in hex.在我的文件中,它上面写着 54,而不是 output 是十六进制的 36。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM