Nevets
Nevets

Reputation: 315

Converting Type Int to Type Byte

I have a small set of code that attempts to bit-shift a 1-bit from the 0 index to the 7 index in a byte. After each bit shift I want to take the int value and convert it to a byte:

for(int t=0; t<8; t++)
{
    int ShiftBit = 0x80 >> t;
    byte ShiftBitByte = Convert.ToByte(ShiftBit.ToString(),8);
}

I would expect the outputs to be:

When I run my code I encounter an exception "Additional non-parsable characters are at the end of the string." Is there a better way to capture these bytes?

Thank you

Upvotes: 2

Views: 604

Answers (3)

phoog
phoog

Reputation: 43046

You're getting the error because you are erroneously specifying that the string is in base 8. The digit '8' is not a legal digit in base 8, which uses only 0 through 7.

Why not

for (byte b = 0x80; b != 0; b >>= 1)

?

Thanks for catching that ... what I really meant to write was shift a bit in int 0x10000000 from index 0 to 7 and then convert it to a byte each time for an array [0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01]. Is that possible?

I don't understand what int 0x10000000 has to do with it. If you want that array, you can achieve that in any of a number of ways:

byte[] xs = { 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 };

byte[] ys = Enumerable.Range(0, 8).Select(i => (byte)(0x80 >> i)).ToArray();

byte[] zs = new byte[8];
for (int index = 0; index < zs.Length; index++)
    zs[index] = (byte)(0x80 >> index);

Upvotes: 2

Nicholas Carey
Nicholas Carey

Reputation: 74267

Why don't do you this?

for ( int i = 0 ; i < 8 ; ++i )
{
  int  s = 0x80 >> i ;
  byte b = (byte) s ;
)

Or (cleaner):

for ( int i = 0x00000080 ; i != 0 ; i >>1 )
{
  byte b = (byte) i ;
}

To turn a byte into a hex string, something like

byte b = ...
string s = string.Format("0x{0:X2}",b) ;

Ought to do you. But a byte is a number, it doesn't have a format (representation) until you turn it into a string a give it one.

Upvotes: 2

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

Are you looking for this ?

for (int t = 0; t < 8; t++)
{
   int ShiftBit = 0x80 >> t;
   byte ShiftBitByte = (byte) ShiftBit;

   Console.WriteLine("0x{0:X}",ShiftBitByte);
}

enter image description here

See Standard Numeric Format Strings

Upvotes: 2

Related Questions