How can I set a byte to hold the binary value 10?

  • Thread starter Thread starter Max Adams
  • Start date Start date
M

Max Adams

How can I set a byte to hold the binary value 10?

Doing this doesn't work, I want to store the code for 10 in 1 byte of
memory.

byte encodedBytes = '10';

Doesn't compile "Too many characters in character literal"

Any thoughts?
 
Max,

If you want a general way to convert the binary representation of a
number to a byte, then use the static ToByte method on the Convert class,
like so:

// Convert "10" to a byte:
byte b = Convert.ToByte("10", 2);

The second parameter is the base to interpret the string in.

Hope this helps.
 
Hi Max,

Well, assuming you mean binary 10 as in decimal 2

byte encodedBytes = 2;

Or

byte encodedBytes = (byte)Convert.ToInt32("10", 2);
 
Ignore my answer and use Nicholas' instead. No need to convert to int when ToByte has a similar overload.

Note though that you can set a byte directly to an integer value, but need to cast it to (byte) if it needs to be evaluated.
 
How can I set a byte to hold the binary value 10?
Doing this doesn't work, I want to store the code for 10 in 1 byte of
memory.

byte encodedBytes = '10';

Doesn't compile "Too many characters in character literal"



To avoid confusion, my post should have read, how do I convert the integer
number 10 (ten) to a one byte representation.
 
Max Adams said:
To avoid confusion, my post should have read, how do I convert the integer
number 10 (ten) to a one byte representation.

Ah. That's easy:

int i = 10;
byte b = (byte)i;

Or just

byte b = 10;
 
Back
Top