在C / C固定长度的数据类型++ [英] fixed length data types in C/C++

查看:114
本文介绍了在C / C固定长度的数据类型++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说过的数据类型的大小,如 INT 可跨平台的不同而不同。

我的第一个问题是:有人可以带来一些例子,什么不顺心,当节目
假设一个 INT 为4个字节,但在不同的平台上是说2个字节?

我有另一个问题是相关的。我知道人们解决这个问题的一些的typedef
就像你有一个像 U8 变量, U16 U32 - 这些都保证是8位,16位,32位,无论平台 - 我的问题是,这是怎么实现的一般? (我不是从 stdint 指的是各种类型的图书馆 - 我手动也很好奇,怎么可以强制执行,一些类型总是说不管是什么平台?32位)


解决方案

  

我知道人们解决这个问题的一些类型定义,就像你有一个像U8,U16,U32的变量 - 这是保证是8位,16位,32位,无论平台


有一些平台,它们没有什么类型的一定规模的(例如像TI的和280x,其中焦炭的大小为16位)。在这种情况下,就不可能有一个8位类型(除非你真的想要它,但可能会引入性能损失)。


  

这是如何实现的,通常?


平时用的typedef。 C99(和C ++ 11)具有这些类型定义在一个头。所以,仅仅使用它们。


  

有人可以带来一些例子,什么不顺心,当程序假定一个int是4字节,但在不同的平台上是说2个字节?


最好的例子就是不同类型的大小系统之间的通信。发送型数组从一个到另一个平台,是sizeof(int)的是在两个不同的,一个人采取极端小心。

此外,节能在32位平台的二进制文件型数组,并reinter preting它在64位平台上。

I've heard that size of data types such as int may vary across platforms.

My first question is: can someone bring some example, what goes wrong, when program assumes an int is 4 bytes, but on a different platform it is say 2 bytes?

Another question I had is related. I know people solve this issue with some typedefs, like you have variables like u8,u16,u32 - which are guaranteed to be 8bits, 16bits, 32bits, regardless of the platform -- my question is, how is this achieved usually? (I am not referring to types from stdint library - I am curious manually, how can one enforce that some type is always say 32 bits regardless of the platform??)

解决方案

I know people solve this issue with some typedefs, like you have variables like u8,u16,u32 - which are guaranteed to be 8bits, 16bits, 32bits, regardless of the platform

There are some platforms, which have no types of certain size (like for example TI's 28xxx, where size of char is 16 bits). In such cases, it is not possible to have an 8-bit type (unless you really want it, but that may introduce performance hit).

how is this achieved usually?

Usually with typedefs. c99 (and c++11) have these typedefs in a header. So, just use them.

can someone bring some example, what goes wrong, when program assumes an int is 4 bytes, but on a different platform it is say 2 bytes?

The best example is a communication between systems with different type size. Sending array of ints from one to another platform, where sizeof(int) is different on two, one has to take extreme care.

Also, saving array of ints in a binary file on 32-bit platform, and reinterpreting it on a 64-bit platform.

这篇关于在C / C固定长度的数据类型++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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