Ada类型大小差异 [英] Ada types size difference

查看:87
本文介绍了Ada类型大小差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个Ada程序:

with Ada.Text_IO, Ada.Integer_Text_IO;
use Ada.Text_IO, Ada.Integer_Text_IO;
procedure test is
type MY_TYPE is new Integer range 1..20;
subtype MY_TYPE2 is MY_TYPE range 5..6;
c : MY_TYPE:=10;
 f : MY_TYPE2 :=6;
 begin
put(Integer(c'SIZE));
 end test;

当我运行它时,我得到32。如果我替换

and when I run it I get 32. If I replace

type MY_TYPE is new Integer range 1..20;

type MY_TYPE is range 1..20;

我得到8。两个声明之间有什么区别?

I get 8. What is the difference between the two declarations?

推荐答案

您允许编译器为这些不同的类型声明选择大小,并且它根据基础类型的大小来选择INTEGER类型的大小。 (INTEGER)。

You are allowing the compiler to choose the sizes for these different type declarations, and it is picking the size of your INTEGER type according to the size of its base type (INTEGER).

您可以控制以下类型的大小:如果将第一个声明重写为

You have control over the sizes of these types : if you rewrite the first declaration as

type MY_TYPE is new Integer range 1..20;
for MYTYPE'SIZE use 8;

您应该获得8位MY_TYPE。

you should get an 8-bit MY_TYPE.

for MYTYPE'SIZE use 5;

应将MYTYPE打包为5位(据我所知,编译器可以使用显式错误,或生成正确的代码,但不接受它并生成垃圾。)

ought to pack MYTYPE into 5 bits (as I understand it, a compiler is permitted to reject this with an explicit error, or generate correct code, but NOT to accept it and generate garbage.)

为什么要打包 MYTYPE 变成5位?原因是它是否用作记录的组成部分:只要它们是布尔值且它们的 SIZE 属性为1,就可以在一个字节中保留3个以上的组成部分的空间。 !

Why would you want to pack MYTYPE into 5 bits? One reason is if it's used as a component of a record : that leaves room for 3 more components in a single byte, as long as they are booleans and their SIZE attribute is 1!

这看起来像是极端打包,但实际上在嵌入式编程中很常见,其中该记录类型与外围设备或I / O端口中的位匹配。您还可以在记录中指定位级布局,例如:

This may look like extreme packing, but it's actually quite common in embedded programming, where that record type matches the bits in a peripheral or I/O port. You would also specify the bit-level layout within the record, as in:

type Prescale is new Integer range 1..20;
for  Prescale'SIZE use 5;

type Timer_Ctrl_Reg is record
   Scale  : Prescale;
   Up     : Boolean;
   Repeat : Boolean;
   Int_En : Boolean;
end record;
for Timer_Ctrl_Reg use record
   Scale  at 0 range 0 .. 4;
   Up     at 0 range 5 .. 5;
   Repeat at 0 range 6 .. 6;
   Int_En at 0 range 7 .. 7;
end record;

at 指定距记录基的偏移量通常以字节或字为单位:范围指定存储单元中的位位置。

at specifies the offset from the record base in "storage units" usually bytes or words : range specifies the bit positions within the storage unit.

没有更多信息狡猾的位掩盖和提取担心!

No more dodgy bit masking and extraction to worry about!

另一方面,

for MYTYPE'SIZE use 4;

应该失败,因为MYTYPE具有16个以上的离散值。

ought to fail, as MYTYPE has more than 16 discrete values.

这篇关于Ada类型大小差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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