字符型,短整型,整型和长整型
char #
字符型在内存里存储1字节(8位元组),允许二进制记录法2^8=256表达值。字符型包括正值和负值,范围在-128-127之间。
uchar #
无字符型和字符型一样,也占据1字节内存,但与之不同的是,它只有正值。最小值是0,最大值是255,无字符型的第一个字母u是unsigned的缩写。
short #
短型数据2字节(16位元组),所以它可以表达等于2的值和16: 2^16 = 65 536,因此短型还是一个符号,包括正值和负值,范围在-32768到32767之间。
ushort #
无符短型是ushort,也占用2字节,最小值是0,最大值是65535。.
int #
整型占用4字节内存(32元组),最小值是-2 147 483 648,最大值是2 147 483 647。
uint #
无符号整型就是uint。它占用4字节内存,区间在0到4 294 967 295之间。
long #
长型占用8字节(64元组),最小值是-9 223 372 036 854 775 808,最大值是9 223 372 036 854 775 807。
ulong #
无符长型也占用8字节,能存储从0到18 446 744 073 709 551 615之间的值。
示例:
char ch=12;
short sh=-5000;
int in=2445777;
|
无符长型不代表短型的负值,建立负值会导致意外的结果,该脚本会无限循环:
//--- 无限循环
void OnStart()
{
uchar u_ch;
for(char ch=-128;ch<128;ch++)
{
u_ch=ch;
Print("ch = ",ch," u_ch = ",u_ch);
}
}
|
正确的转化是:
//--- 正确的变量
void OnStart()
{
uchar u_ch;
for(char ch=-128;ch<=127;ch++)
{
u_ch=ch;
Print("ch = ",ch," u_ch = ",u_ch);
if(ch==127) break;
}
}
|
结果:
ch= -128 u_ch= 128
ch= -127 u_ch= 129
ch= -126 u_ch= 130
ch= -125 u_ch= 131
ch= -124 u_ch= 132
ch= -123 u_ch= 133
ch= -122 u_ch= 134
ch= -121 u_ch= 135
ch= -120 u_ch= 136
ch= -119 u_ch= 137
ch= -118 u_ch= 138
ch= -117 u_ch= 139
ch= -116 u_ch= 140
ch= -115 u_ch= 141
ch= -114 u_ch= 142
ch= -113 u_ch= 143
ch= -112 u_ch= 144
ch= -111 u_ch= 145
...
|
示例:
//--- 负值不能存储在无符类型中
uchar u_ch=-120;
ushort u_sh=-5000;
uint u_in=-401280;
|
十六进制:数字0-9,字母a-f,或A-F表示值10-15,从0x或0X开始。
示例:
0x0A, 0x12, 0X12, 0x2f, 0xA3, 0Xa3, 0X7C7
|
对于整型变量,值可以使用B前缀以二进制格式设置。例如,您可以编码交易时间的工作小时为int类型变量并根据所需的算法使用他们的信息:
//+------------------------------------------------------------------+
//| 脚本程序开始函数 |
//+------------------------------------------------------------------+
void OnStart()
{
//--- 设置 1 为工作小时和 0 为非工作小时
int AsianSession =B'111111111'; // 亚洲时间从 0:00 到 9:00
int EuropeanSession=B'111111111000000000'; // 欧洲时间 9:00 - 18:00
int AmericanSession =B'111111110000000000000011'; // 美洲时间 16:00 - 02:00
//--- 派生时间数值
PrintFormat("Asian session hours as value =%d",AsianSession);
PrintFormat("European session hours as value is %d",EuropeanSession);
PrintFormat("American session hours as value is %d",AmericanSession);
//--- 现在让我们展示时间工作小时的字符串表示
Print("Asian session ",GetHoursForSession(AsianSession));
Print("European session ",GetHoursForSession(EuropeanSession));
Print("American session ",GetHoursForSession(AmericanSession));
//---
}
//+------------------------------------------------------------------+
//| 返回时间工作小时为字符串 |
//+------------------------------------------------------------------+
string GetHoursForSession(int session)
{
//--- 若要检查,使用AND比特操作并左移1比特<<=1
//--- 从最小比特开始检查
int bit=1;
string out="working hours: ";
//--- 从零开始检查全部24比特并最高到23
for(int i=0;i<24;i++)
{
//--- 总共接收的比特数
bool workinghour=(session&bit)==bit;
//--- 添加小时数到嘻嘻
if(workinghour )out=out+StringFormat("%d ",i);
//--- 左移1比特检查下一个的值
bit<<=1;
}
//--- 结果字符串
return out;
}
|
另见:
类型转换