Hello, I am making a program that reads a bin file and stores it in a char array.
Then I have to check each char value to then decided what to do.
For instance, for the first array, this works for me
case'x': {
However, second character is 'D8'
so if I do a:
case'D8': {
it will give a warn:
1 2
warning: multi-character character constant [-Wmultichar]
case'D8':[
and it does not work.
I suppose I can compare it to a int value, however, to make my life easier compared to what the hex editor shows me, I would like to compare it to a hex representation like 'D8'. Also, I would like to be able to print such representation in the screen.
#include <iostream>
#include <iomanip>
#include <fstream>
int main()
{
std::ifstream fin("bin01.bin", fin.binary);
// Set cout to display integers as hex, using uppercase letters,
// and with '0' instead of ' ' as the fill character for std::setw.
// https://en.cppreference.com/w/cpp/io/manip
std::cout << std::hex << std::uppercase << std::setfill('0');
for (char ch; fin.get(ch); )
{
switch (ch)
{
case'x':
std::cout << "found x\n";
break;
case'\xD8':
std::cout << "found 0xD8\n";
break;
}
// First convert the char, which may be signed, to an unsigned char.
// Then convert that to int. Output with a 2-digit fieldwidth.
std::cout << "0x" << std::setw(2) << (int)(unsignedchar)ch << '\n';
}
}
@jonnin, Before the char is compared to the int 0xD8, the char is converted to an int. If char is signed and above 0x7F it will be negative and therefore converted into a negative (sign-extended) int, and so will not equal 0xD8.
1 2 3
// Prints "nope" if char is signed.
#include <iostream>
int main() { std::cout << ('\xD8' == 0xD8 ? "yep\n" : "nope\n"); }