SV——类型转换
0. 介绍
在SV中类型转换有很多,在这里先将类型转换分成两种,静态类型转换和动态转换。
静态转换就是用cast operator——单引号(‘)。
动态转换用$cast。
1. 静态转换 static cast(’)
语法如下:
1 |
|
如果casting_type和表达式类型相同,那么会返回casting_type类型的值给到左值。如果类型不匹配,也会强行转换(string类型也会转换成int类型),但会出现问题:
casting_type是枚举类型,转换可能出界。
1
2
3
4
5
6
7
8typedef enum {RED,BLUE,GREEN} color_e;
color_e color;
int c;
initial begin
c=10;
color=color_e'(c);
end上面的转换会成功,color的值变成10,但这除了color_e这个枚举类型的界限了。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19typedef enum {RED,BLUE,GREEN} COLOR_E;
COLOR_E color;
int c;
string str;
initial begin
str="hh";
c=int'(str);
$display("c is %0d",c);
c=1;
color=COLOR_E'(c);
$display("Color is %d / %s",color,color.name);
c=3;
color=COLOR_E'(c);
$display("Color is %d / %s",color,color.name);
end
// 输出
c is 26728
Color is 1 / BLUE
Color is 3 /从上面输出可以看出string类型转换成了int值;第二个color越界了。
casting_type是bit_stream type。
比特流类型先不整理了,没遇到过,在1800 6.24.3节,如果以后遇到再看吧。
2. 动态转换($cast)
上面static cast不会检查表达式的类型,可能会发生string转换成int,枚举越界等问题。
动态转换$cast可以作为function,也可以作为task(这个问题地平线一面的时候被问过,$cast是函数还是任务),语法如下:
1 |
|
Use of $cast as either a task or a function determines how invalid assignments are handled.
When called as a task, $cast attempts to assign the source expression to the destination variable. If the
assignment is invalid, a run-time error occurs, and the destination variable is left unchanged.
When called as a function, $cast attempts to assign the source expression to the destination variable and returns 1 if the cast is legal. If the cast fails, the function does not make the assignment and returns 0. When called as a function, no run-time error occurs, and the destination variable is left unchanged.
It is important to note that $cast performs a run-time check. No type checking is done by the compiler, except to check that the destination variable and source expression are singulars.
至于$cast是作为function还是task,主要看$cast使用的语境是否需要返回值。
$cast作为function
1 |
|
第二次$cast失败之后,color的值不变。
$cast作为task
1 |
|
$cast先进行类型判断,再转化。
3. 其他类型转换
在IEEE 1800的20.5节中,还介绍了一些integer2string或者signed2unsigned的函数
$itor converts integer values to real values (for example, 123 becomes 123.0).
$realtobits converts values from a real type to a 64-bit vector representation of the real number.
$bitstoreal converts a bit pattern created by $realtobits to a value of the real type.
$shortrealtobits converts values from a shortreal type to the 32-bit vector representation of the real number.
$bitstoshortreal converts a bit pattern created by $shortrealtobits to a value of the shortreal type
$signed—returned value is signed
$unsigned—returned value is unsigned
1 |
|
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!