Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast a number to a byte?

Tags:

c#

casting

In C and C++ you can tell the compiler that a number is a 'long' by putting an 'l' at the end of the number. e.g long x = 0l;

How can I tell the C# compiler that a number is a byte?

like image 401
Robert Avatar asked Sep 30 '08 14:09

Robert


People also ask

How do you convert numbers to bytes?

Basically, to do a bit to byte conversion, you take an 8 bit binary number and form it into groups of 4 bits (nibbles). You then translate each nibble into a hexadecimal number (a 2 hex digit byte) using this table. You then multiply the left digit by 16 and add the result to the first digit.

Can you cast an int to a byte?

An int value can be converted into bytes by using the method int. to_bytes().

How do you convert int to byte value?

Solution 1. int intValue = 2; byte byteValue = Convert. ToByte(intValue);

What is byte casting?

In Java, there are two types of casting: Widening Casting (automatically) - converting a smaller type to a larger type size. byte -> short -> char -> int -> long -> float -> double. Narrowing Casting (manually) - converting a larger type to a smaller size type. double -> float -> long -> int -> char -> short -> byte.

How many values can a byte have?

A byte is not just 8 values between 0 and 1, but 256 (28) different combinations (rather permutations) ranging from 00000000 via e.g. 01010101 to 11111111 . Thus, one byte can represent a decimal number between 0(00) and 255. Puzzled?


3 Answers

byte b = (byte) 123; 

even though

byte b = 123;

does the same thing. If you have a variable:

int a = 42;
byte b = (byte) a;
like image 117
Sklivvz Avatar answered Sep 19 '22 10:09

Sklivvz


According to the C# language specification there is no way to specify a byte literal. You'll have to cast down to byte in order to get a byte. Your best bet is probably to specify in hex and cast down, like this:

byte b = (byte) 0x10;
like image 36
Douglas Mayle Avatar answered Sep 22 '22 10:09

Douglas Mayle


Remember, if you do:

byte b = (byte)300;

it's not going to work the way you expect.

like image 34
casademora Avatar answered Sep 20 '22 10:09

casademora