C#中的十六进制符号和有符号整数 [英] Hexadecimal notation and signed integers in C#

查看:804
本文介绍了C#中的十六进制符号和有符号整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是跟进问题。因此,Java商店的整数在两个补充中,您可以执行以下操作:

  int ALPHA_MASK = 0xff000000; 

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



我的问题,如何在c#中以十六进制表示法声明负值,以及整数在内部表示的确切程度如何?这里和Java有什么不同?

解决方案

C#(相当于.NET)也使用了二者的补充,但它同时支持有符号和无符号类型(Java没有)。一个位掩码更自然地是一个无符号的事情 - 为什么一个位应该与其他所有位不同?

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

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

要直接将此数字表示为有符号值,您需要写入

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

十六进制不是(或不应该)与小数点不同:to代表一个负数,你需要写一个负号,然后是代表绝对值的数字。


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

int ALPHA_MASK = 0xff000000;

In C# this requires the use of an unsigned integer, uint, because it interprets this to be 4278190080 instead of -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# (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?

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.

这篇关于C#中的十六进制符号和有符号整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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