int8_t 与 char ;哪个是最好的? [英] int8_t vs char ; Which is the best one?

查看:13
本文介绍了int8_t 与 char ;哪个是最好的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道两者都是不同的类型(signed charchar),但是我公司的编码指南指定使用 int8_t 而不是 char.

I know both are different types (signed char and char), however my company coding guidelines specifies to use int8_t instead of char.

所以,我想知道,为什么我必须使用 int8_t 而不是 char 类型.有没有使用 int8_t 的最佳实践?

So, I want to know, why I have to use int8_t instead of char type. Is there any best practices to use int8_t?

推荐答案

在某些情况下使用 int8_t 非常好 - 特别是当类型用于计算有符号的 8 位值时是必须的.涉及严格大小数据的计算[例如由外部要求定义为在结果中精确为 8 位](我在上面的评论中使用了像素颜色级别,但这实际上是 uint8_t,因为负像素颜色通常不存在 - 除了也许在 YUV 类型的色彩空间中).

The use of int8_t is perfectly good for some circumstances - specifically when the type is used for calculations where a signed 8-bit value is required. Calculations involving strictly sized data [e.g. defined by external requirements to be exactly 8 bit in the result] (I used pixel colour levels in a comment above, but that really would be uint8_t, as negative pixel colours usually don't exist - except perhaps in YUV type colourspace).

int8_t 类型不应用作字符串中 char 的替代品.这可能导致编译器错误(或警告,但我们也不想处理来自编译器的警告).例如:

The type int8_t should NOT be used as a replacement of char in for strings. This can lead to compiler errors (or warnings, but we don't really want to have to deal with warnings from the compiler either). For example:

int8_t *x = "Hello, World!
";

printf(x);

可能在编译器 A 上编译得很好,但在编译器 B 上混合有符号和无符号 char 值时会给出错误或警告.或者如果 int8_t 甚至没有使用 char 类型.这就像期待

may well compile fine on compiler A, but give errors or warnings for mixing signed and unsigned char values on compiler B. Or if int8_t isn't even using a char type. That's just like expecting

int *ptr = "Foo";

在现代编译器中编译...

to compile in a modern compiler...

换句话说,如果您使用 8 位数据进行计算,则应该使用 int8_t 而不是 char.将所有 char 全部替换为 int8_t 是不正确的,因为它们远不能保证相同.

In other words, int8_t SHOULD be used instead of char if you are using 8-bit data for caclulation. It is incorrect to wholesale replace all char with int8_t, as they are far from guaranteed to be the same.

如果需要对字符串/文本/等使用char,并且由于某种原因char 过于模糊(可以有符号或无符号等), 然后使用 typedef char mychar; 或类似的东西.(有可能找到比 mychar 更好的名字!)

If there is a need to use char for string/text/etc, and for some reason char is too vague (it can be signed or unsigned, etc), then usign typedef char mychar; or something like that should be used. (It's probably possible to find a better name than mychar!)

我应该指出,无论你是否同意这一点,我认为简单地走到公司负责这一原则"的任何人面前,指着关于 SO 和说我认为你错了".尝试了解动机是什么.它可能比看起来更多.

I should point out that whether you agree with this or not, I think it would be rather foolish to simply walk up to whoever is in charge of this "principle" at the company, point at a post on SO and say "I think you're wrong". Try to understand what the motivation is. There may be more to it than meets the eye.

这篇关于int8_t 与 char ;哪个是最好的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆