C# 十六进制表示法和有符号整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/319993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 23:03:25  来源:igfitidea点击:

Hexadecimal notation and signed integers

c#typeshex

提问by kitsune

This is a follow up question. So, Java store's integers in two's-complementsand you can do the following:

这是一个后续问题。因此,Java 以二进制补码形式存储整数,您可以执行以下操作:

int ALPHA_MASK = 0xff000000;

In C# this requires the use of an unsigned integer, uint, because it interprets this to be 4278190080instead of -16777216.

在 C# 中,这需要使用无符号整数uint,因为它将其解释为4278190080而不是-16777216

My question, how do declare negative values in hexadecimal notation in c#, and how exactly are integers represented internally? What are the differences to Java here?

我的问题是,如何在 c# 中以十六进制表示法声明负值,以及内部如何准确表示整数?这里与Java有什么区别?

采纳答案by Martin v. L?wis

C# (rather, .NET) also uses the two's complement, but it supports both signed and unsigned types (which Java doesn't). A bit mask is more naturally an unsigned thing - why should one bit be different than all the other bits?

C#(更确切地说,.NET)也使用二进制补码,但它同时支持有符号和无符号类型(Java 不支持)。位掩码更自然地是无符号的东西 - 为什么一位应该与所有其他位不同?

In this specific case, it is safe to use an unchecked cast:

在这种特定情况下,使用未经检查的强制转换是安全的:

int ALPHA_MASK = unchecked((int)0xFF000000);

To "directly" represent this number as a signed value, you write

要“直接”将此数字表示为有符号值,请编写

int ALPHA_MASK = -0x1000000; // == -16777216

Hexadecimal is not (or should not) be any different from decimal: to represent a negative number, you need to write a negative sign, followed by the digits representing the absolute value.

十六进制与十进制没有(或不应该)任何不同:要表示负数,您需要写一个负号,后跟表示绝对值的数字。

回答by Marc Gravell

Well, you can use an unchecked block and a cast:

好吧,您可以使用未经检查的块和强制转换:

unchecked
{
    int ALPHA_MASK = (int)0xff000000;
}

or

或者

int ALPHA_MASK = unchecked((int)0xff000000);

Not terribly convenient, though... perhaps just use a literal integer?

不过不是很方便……也许只是使用文字整数?

回答by Quadko

And just to add insult to injury, this will work too:

只是为了雪上加霜,这也行得通:

-0x7F000000