Should a buffer of bytes be signed or unsigned cha

2019-01-21 03:23发布

Should a buffer of bytes be signed char or unsigned char or simply a char buffer? Any differences between C and C++?

Thanks.

标签: c++ c char buffer
14条回答
我欲成王,谁敢阻挡
2楼-- · 2019-01-21 03:34

If you fetch an element into a wider variable, it will of course be sign-extended or not.

查看更多
我命由我不由天
3楼-- · 2019-01-21 03:35

You should use either char or unsigned char but never signed char. The standard has the following in 3.9/2

For any object (other than a base-class subobject) of POD type T, whether or not the object holds a valid value of type T, the underlying bytes (1.7) making up the object can be copied into an array of char or unsigned char.If the content of the array of char or unsigned char is copied back into the object, the object shall subsequently hold its original value.

查看更多
ら.Afraid
4楼-- · 2019-01-21 03:35

Do you really care? If you don't, just use the default (char) and don't clutter your code with unimportant matter. Otherwise, future maintainers will be left wondering why did you use signed (or unsigned). Make their life simpler.

查看更多
乱世女痞
5楼-- · 2019-01-21 03:37

For maximum portability always use unsigned char. There are a couple of instances where this could come into play. Serialized data shared across systems with different endian type immediately comes to mind. When performing shift or bit masking the values is another.

查看更多
Rolldiameter
6楼-- · 2019-01-21 03:37

The choice of int8_t vs uint8_t is similar to when you are comparing a ptr to be NULL.


From a functionality point of view, comparing to NULL is the same as comparing to 0 because NULL is a #define for 0.

But personally, from a coding style point of view, I choose to compare my pointers to NULL because the NULL #define connotes to the person maintaining the code that you are checking for a bad pointer...

VS

when someone sees a comparison to 0 it connotes that you are checking for a specific value.


For the above reason, I would use uint8_t.

查看更多
啃猪蹄的小仙女
7楼-- · 2019-01-21 03:43

Should and should ... I tend to prefer unsigned, since it feels more "raw", less inviting to say "hey, that's just a bunch of small ints", if I want to emphasize the binary-ness of the data.

I don't think I've ever used an explicit signed char to represent a buffer of bytes.

Of course, one third option is to represent the buffer as void * as much as possible. Many common I/O functions work with void *, so sometimes the decision of what integer type to use can be fully encapsulated, which is nice.

查看更多
登录 后发表回答