This question already has answers here:
C++ cout hex format
(3 answers)
Closed 9 years ago.
I'm trying to output a hex value assigned to a variable x and I can't seem to get it working in C++. I can do it in standard C but am getting undesired results in C++.
#include <iostream>
#include <iomanip>
using namespace std;
int main(int argc, const char * argv[])
{
unsigned char x = 0xFF;
printf("%X\n", x);
cout << dec << x << endl;
cout << hex << x << endl;
return 0;
}
prints
FF
\377
\377
Because it's unsigned char, the stream thinks you want to output a character, rather than its value. Try casting to int
cout << hex << (int)x << endl;
You might also want to use setw(2) and setfill('0') stream modifiers to pad single-digit hex numbers to 2 digits (similar to using %02X with printf).
Related
This question already has an answer here:
Inlining the UnrealEngine UE_LOG macro with C++
(1 answer)
Closed 9 months ago.
I am following a tutorial in which they use BIO_printf(bio_out,"%02x",bs->data[i] ); in order to get the characters of a serial number stored in bs->data (which is an array of unsigned char) and they use "%02x" to specify the format of the char. I am using c++ and I want to add each of these chars to a stringstream but I can't find a way to translate the format and instead of a serial number I get ጄ냾�㮚㭖嵺ﭔ촋ᙰ.
I have tried using
std::stringstream serial("Serial: ");
for (int i = 0; i < bs->length; i++)
{
serial << std::setw(2) << std::hex << bs->data[i] << std::endl;
}
but I still don't get a valid string, and
char* buffer = const_cast<char*>(serial.str().c_str());
sprintf(buffer, "%02x", bs->data[i]);
doesn't seem to work either (don't mind the const cast, I know it is bad practice)
You can use a combination of the std::setw(), std::setfill() and std::hex manipulators to set the width and fill characters. Also, you need to explicitly cast a char variable to an int in order to get the numerical representation, otherwise the << operator (on a char) will output (or attempt to output) the represented character.
Here's a short example using the std::cout stream (though the manipulators work in the same way on a std::stringstream object):
#include <iostream>
#include <iomanip>
int main()
{
char c = 13;
std::cout << std::setfill('0') << std::setw(2) << std::hex << static_cast<int>(c) << std::endl; // Shows 0d
return 0;
}
This question already has answers here:
String plus Char - what is happening?
(5 answers)
C++. Why std::cout << char + int prints int value?
(2 answers)
cout and String concatenation
(3 answers)
How object cout prints multiple arguments?
(4 answers)
Closed 10 months ago.
I was experimenting with a statement in C++ using online compilers. When I try to run this specific code
cout << num[i] + " " + num[i];
The online compilers give no output. I can change the + symbol to << but I want to know the reason that the code does not give any output on these online compilers.
Online compilers that I tried are onlinegdb, programiz, and jdoodle.
#include <iostream>
#include <string>
int main() {
std::string num = "123";
int i = 0;
std::cout << num[i] + " " + num[i];
return 0;
}
C++ is not like JavaScript or many higher-level languages, as in you may not delimit you data with +'s or ,'s. As shown in Lewis' answer, each item you wish to have printed must be separated by an insertion delimiter (<<). As for extracting, you may use the extraction delimiter (>>).
In your case, you are doing mathematical operations on the the characters themselves (adding together their numerical ASCII representations together, which could print unprintable and invisible characters). The printable ASCII characters range from 32 (space character) to 127 (delete character) (base 10). When summing '1' + ' ' + '1' you are left with (49 + 32 + 49) or (130) which exceeds the printable character range. Or you may also be accessing garbage as #pm100 said in the comments due to pointer arithmetic.
Here is an example of using the insertion operator:
#include <iostream>
int main(void) {
int some_int = 1;
std::cout << "this is my " << some_int << "st answer on StackOverflow :)"
<< std::endl;
return 0;
}
And as for the extraction operator:
#include <iostream>
int main(void) {
int num;
std::cout << "Enter an integer: ";
std::cin >> num; // stores the input into the `num` variable
std::cout << "The number is: " << num << std::endl;
return 0;
}
Pointer arithmetic:
const char* get_filename(const char* _path, size_t _offset) {
return (_path + _offset);
}
// This is an example
//
// path = "path/to/my/file/file.txt";
// offset ^ ^
// 0 |
// + 16 ------------|
// path = "file.txt";
This question already has answers here:
Integer to hex string in C++
(27 answers)
Closed 5 years ago.
I have an int which I want to convert to a char array, but I want the char array to be formatted in hexadecimal and with every byte of the int taking up exactly 2 char variables (filled out with zeroes).
To clarify what I mean, I have an example:
I want the int 232198 (0x38b06) to become "00038b06".
I can of course acomplish this by using this code:
#include <iostream>
#include <iomanip>
int main()
{
std::cout <<
std::hex <<
std::setw(8) <<
std::setfill('0') <<
232198 <<
std::endl;
return 0;
}
Which prints out:
00038b06
But that only prints it out to the console, and as I mentioned before, want to store it a char array.
I don't care if the code is portable or not, this just has to work for windows.
stringstreams are useful to do this:
std::stringstream sstr;
sstr <<
std::hex <<
std::setw(8) <<
std::setfill('0') <<
232198;
std::string str = sstr.str();
now str contains the formatted number. str.c_str() will give you a const char*.
I am a high school beginner to C++ (Less than 1 month since I started). I have been trying to convert a int into its char value. (So, a 5 should convert to a '5')
I am aware how to convert from char to int (from '5' to 5), by subtracting 48 from it, however I am unable to cast the other way. Here's what I tried:
#include <iostream>
using namespace std;
int main()
{
int x = 5;
cout<<x<<endl;
cout<<(char)x<<endl;
cout<<static_cast<char>(x)<<endl;
cout<<"end of program"<<endl;
}
The output I get is
5
end of program
I am unsure why I don't get an output. Appreciate any advice.
The cast is working perfectly fine (for what you're doing).
You're casting a 5 to it's ASCII value. Look at an ASCII table and see what a 5 represents.
Now for what you're trying to do, try cout << (char)(x+48) << endl;
Try the following
#include <iostream>
using namespace std;
int main()
{
int x = 5;
cout << x << endl;
cout << ( char )( x + '0' ) << endl;
cout << static_cast<char>( x + '0' ) < <endl;
cout << "end of program" < <endl;
}
And you have not to look through ASCII table.:) Take into account that there is EBCDIC table. The code I showed does not depend on a coding table. The C++ Standard guarantees that all characters of digits follow each other starting from '0' to '9'.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how do I print an unsigned char as hex in c++ using ostream?
Convert ASCII string into Decimal and Hexadecimal Representations
I want to print out the hex value of characters using isprint(). However, I cannot get it to work. This is my attempt:
getline(cin, w);
for(unsigned int c = 0; c < w.size(); c++)
{
if(!isprint(w[c]))
{
cout << "ERROR: expected <value> found " << hex << w[c] << endl;
return 0;
}
}
Can anyone help me print out this hex value? Thanks! I'm inputting things like:
í
and I want it's hex value.
By default, a char is printed as an string character. Try casting the char to a general int like this:
cout << "ERROR: expected <value> found " << hex << static_cast<int>(w[c]) << endl;