Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hexadecimal notation and signed integers

Tags:

c#

types

hex

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?

like image 928
kitsune Avatar asked Nov 26 '08 07:11

kitsune


People also ask

Is hexadecimal signed or unsigned?

A hexadecimal value is int as long as the value fits into int and for larger values it is unsigned , then long , then unsigned long etc. See Section 6.4. 4.1 of the C standard. Just as the accepted answer states.

What are hexadecimal integers?

A hexadecimal integer literal begins with the 0 digit followed by either an x or X, followed by any combination of the digits 0 through 9 and the letters a through f or A through F. The letters A (or a) through F (or f) represent the values 10 through 15, respectively.

What is signed integer?

A signed integer is a 32-bit datum that encodes an integer in the range [-2147483648 to 2147483647]. An unsigned integer is a 32-bit datum that encodes a nonnegative integer in the range [0 to 4294967295].

What is a signed integer example?

Obviously they are signed integers like +34, -15, -23,and +17. These numbers along with their sign have to be represented in a computer using only binary notation orbits. The simplest way of representing a signed number is the sign magnitude(SM) method.


1 Answers

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.

like image 54
Martin v. Löwis Avatar answered Oct 07 '22 17:10

Martin v. Löwis