Hava Darabi
Hava Darabi

Reputation: 537

how does this assignment work in c#?

My question is that how does this assignment happen in c#? I mean, how does it calculate the answer 1 (with 257), and how does it calculate 0(with 256)?

the code is:

int intnumber=257;
byte bytenumber=(byte)intnumber;//the out put of this code is 1

int intnumber=256;
byte bytenumber=(byte)intnumber;//the out put of this code is 0

My question is what happen,that the output in first code is:1 and in second one is:0

Upvotes: 1

Views: 200

Answers (5)

A byte only occupies one byte in memory. An int occupies 4 bytes in memory. Here is the binary representation of some int values you've mentioned:

      most significant           least significant
 255: 00000000 00000000 00000000 11111111
 256: 00000000 00000000 00000001 00000000
 257: 00000000 00000000 00000001 00000001

You can also see how this works when casting negative int values to a byte. An int value of -255, when cast to a byte, is 1.

-255:  11111111 11111111 11111111 00000001

When you cast an int to a byte, only the least significant byte is assigned to the byte value. The three higher significance bytes are ignored.

Upvotes: 10

McAden
McAden

Reputation: 13970

A single byte only goes up to 255. The code wraps around to 0 for 256 and 1 for 257, etc...

The most significant bits are discarded and you're left with the rest.

Upvotes: 8

Fede
Fede

Reputation: 44068

255 is the maximum value that can be represented in a single byte:

Hex code: FF

256 does not fit in 1 byte. It takes 2 bites to represent that:

01 00

since you're trying to put that value in a variable of type byte (which of course may only contain 1 byte), the second byte is "cropped" away, leaving only:

00

Same happens for 257 and actually for any value.

Upvotes: 2

T-moty
T-moty

Reputation: 2797

1 is assigned because the arithmetic overflow of byte values (max 255) exceed by 2 unit.

0 is assigned because exceed by 1 unit.

Upvotes: 1

EZLearner
EZLearner

Reputation: 1834

the byte data type contains a number between 0 to 255. When converting an int to byte, it calculates the number modulo 256.

byte = int % 256

Upvotes: 0

Related Questions