Why “cout” works weird for “unsigned char”?

你离开我真会死。 提交于 2019-11-27 04:08:24

问题


I have the following code:

cvtColor (image, image, CV_BGRA2RGB);
Vec3b bottomRGB;
bottomRGB=image.at<Vec3b>(821,1232);

When I display bottomRGB[0], it displays a value greater than 255. What is the reason for this?


回答1:


As you have commented, the reason is that you use cout to print its content directly. Here I will try to explain to you why this will not work.

cout << bottomRGB[0] << endl;

Why "cout" works weird for "unsigned char"?

It will not work because here bottomRGB[0] is a unsigned char (with value 218), cout actually will print some garbage value (or nothing) as it is just a non-printable ASCII character which is getting printed anyway. Note that ASCII character corresponding to 218 is non-printable. Check out here for the ASCII table.

P.S. You can check whether bottomRGB[0] is printable or not using isprint() as:

cout << isprint(bottomRGB[0]) << endl; // will print garbage value or nothing

It will print 0 (or false) indicating the character is non-printable


For your example, to make it work, you need to type cast it first before cout:

cout << (int) bottomRGB[0] << endl; // correctly printed (218 for your example) 


来源:https://stackoverflow.com/questions/21374773/why-cout-works-weird-for-unsigned-char

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!