为什么"cout"对"unsigned char"很奇怪?

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

本文关键字:unsigned cout 为什么 char      更新时间:2023-10-16

我有以下代码:

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

当我显示 bottomRGB[0]时,它显示一个大于255的值。

的原因是什么?

正如您所评论的,原因是您使用cout直接打印其内容。在这里,我将尝试向您解释为什么这不起作用。

cout << bottomRGB[0] << endl;

为什么"cout""unsigned char"工作很奇怪?

它将不起作用,因为bottomRGB[0]unsigned char(具有值218),cout实际上会打印一些垃圾值(或没有),因为它只是 non--无论如何都会打印出可打印的ASCII字符。请注意,与218相对应的ASCII字符是不可打印的。在此处查看ASCII表。

P.S。您可以检查bottomRGB[0]是否可以使用isprint()为:

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

它将打印0(或false),表明该字符是不可打印的


为了您的示例,要使它起作用,您需要在cout之前先键入铸件:

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