2

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:

  • 0x80
  • 0x40
  • 0x20
  • 0x10
  • 0x08
  • 0x04
  • 0x02
  • 0x01

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

1
  • 1
    Why don't you just cast to byte or am I missing something? Commented Jan 28, 2014 at 22:37

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your feedback. I guess what I am really trying to do is shift a 1 as follows: 10000000 (or 0x80), 01000000 (or 0x40) .... 0x00000001 (or 0x01). Once each bit is shifted I want to capture it in hex format "0x--".
2

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

Comments

2

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); 

2 Comments

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?
@Nevets I've updated my answer to address your question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.