简体   繁体   English

整数文字如何存储?

[英]How are integer literals stored?

Does a small integer literal in C# (eg 12 ) uses 4 bytes of stack like an integer variable‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌? C#中的一个小的整数文字(例如12 )是否像整数变量一样使用4个字节的堆栈? Does it need 4 bytes? 需要4个字节吗?

Does a short integer literal in C# ... 在C#中执行短整数文字...

You cannot declare a literal of type short so the question is iffy. 您无法声明类型为short的文字,因此问题很棘手。 In practice, the C# compiler will treat it like an int (or long if large enough) and readily convert it to byte or short where appropriate without a cast. 实际上,C#编译器会将其视为int (如果足够大则为long ),并在不进行强制转换的情况下将其轻松转换为byteshort And complain when such a conversion causes an overflow. 并抱怨这种转换导致溢出。

It will end up getting encoded in a processor instruction like MOV or PUSH, depending on how you use the literal. 它最终将被编码为MOV或PUSH之类的处理器指令,具体取决于您使用文字的方式。 A practical example, use the Debug > Windows > Disasssembly window to see it: 一个实际示例,请使用“调试”>“ Windows”>“反汇编”窗口进行查看:

    static void Main(string[] args) {
        Console.WriteLine(12);
    }

Generates: 产生:

  005B2DB0 B9 0C 00 00 00       mov         ecx,0Ch  
  005B2DB5 E8 7E 38 BE 72       call        73196638  
  005B2DBA C3                   ret  

Note the MOV instruction and the instruction bytes it generates. 注意MOV指令及其生成的指令字节。 B9 is the "move 32-bit immediate" instruction, the next 4 bytes are the value in little-endian order. B9是“移动32位立即数”指令,接下来的4个字节是小端顺序的值。 Otherwise selected because the C# compiler used the WriteLine(Int32) overload, it does not have overloads for byte or short . 否则选择该选项,因为C#编译器使用WriteLine(Int32)重载,它没有byteshort的重载。 Use the same technique to see what happens with your specific code. 使用相同的技术来查看您的特定代码会发生什么。

You can't declare a short numeric literal. 您不能声明short数字文字。 You can only declare numeric literals of types int , float ( f suffix), double ( d suffix), uint ( u suffix), long ( l suffix), ulong ( ul suffix) and decimal ( m suffix). 您只能声明类型为intfloatf后缀), doubled后缀), uintu后缀), longl后缀), ulongul后缀)和decimalm后缀)的数字文字。

All numeric literals without suffixes eg 12 are inferred to be of the first of these types in which their value can be represented: int , uint , long , ulong . 所有不带后缀的数字文字(例如12都被推断为其中可以表示其值的第一个类型: intuintlongulong so if 12 were put on the stack, it would require 4 bytes on a 32-bit system. 因此, 如果将 12个放在堆栈上,则在32位系统上将需要4个字节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM