Initial data: There is a binary file which we read ifstream in (FName, ifstream::binary); . There is a structure containing char type fields. char a[8]; It is necessary to read the file into the structure and output hex ;. Do so

 ifstream in (FName, ifstream::binary); in.read((char*)&X, sizeof X); //效懈褌邪械屑 褋褌褉褍泻褌褍褉褍 int len1=in.gcount(); ofstream fout(FName1); fout << "袩芯谢械="; for(int i = 0; i <= 7; i++) { fout<<setfill ('0')<<setw(2)<<hex<<(int)Xa[i]; }; 

When outputting in the byte, there appears an extra ffffff.

Question: How to get rid of extra characters?

    1 answer 1

    Try leading to the unsigned char type:

     cout << static_cast<int>(*reinterpret_cast<unsigned char*>(&a[i])); 

    The explanation for this phenomenon is that in your c ++ char compiler implementation is a signed type, and when you cast it to an int , you get a negative number. And you have a negative number encoded in the additional code, hence a bunch of unit bits.

    The first conversion is a hard type conversion - we simply force the compiler to treat the bytes at this address as an unsigned char type - to an unsigned character of the same dimension.

    For greater stiffness, you can write somewhere in the program:

     static_assert(sizeof(char)==sizeof(unsigned char),"wrong signed/unsigned char size!"); 

    The second conversion is, in fact, creating a new anonymous variable of type int , into which the value obtained in the first step is written.

    The cast to int type is necessary so that iostream to interpret the output as a number, not as a symbol.

    • "char - sign type" - this is not a fact. - free_ze
    • one
      type sizes do not change due to the presence or absence of sign. Yes, and your reinterpret_cast does not work, even if shar replaced by char . - 伪位蔚蠂慰位蠀蟿
    • @alexolut is if the compiler is friendly with the standard. Of course, verification is unnecessary, but since it is done at compile time, I don鈥檛 see any special problems to keep it - gbg
    • There are some basic things that all c ++ compilers should be friends with, regardless of following the Standard. Can you give an example where the size changes from sign-meaning or is it an extension of the compiler? - 伪位蔚蠂慰位蠀蟿
    • The caste still lacks & * . - 伪位蔚蠂慰位蠀蟿