0

I have a 4 byte value that I convert to an Int32 and then display it in a textbox. No problems there. The problem comes in when I try padding the string with 0's. When I display the decimal number it should always contain 8 characters, so if its less than that I want to pad it with 0's.

string parmDecString = BitConverter.ToInt32(testNum, 0).ToString();
Console.WriteLine("length: {0} - {1}", parmDecString.Length, (8 - parmDecString.Length));
for (int l=0; l < (8-parmDecString.Length); l++)
{
    parmDecString = "0" + parmDecString;
}
textBox74.Text = parmDecString;

Here's the output in the textbox I get based on different 'parmDecString' values:

parmDecString = "123"
Console:  length: 3 - 5
textbox:  000123   <=== only 3 times in the 'for' loop, expected 5x

parmDecString = "12345"
Console:  length: 5 - 3
textbox:  0012345   <=== only 2 times in the 'for' loop, expected 3x

parmDecString = "12345678"
Console:  length: 8 - 0
textbox:  12345678   <=== as expected
5

4 Answers 4

6

First off, the right answer to this is just use the provided format strings. In your case, if you stored the number as paramDec you would use paramDec.ToString("D8"); for an 8-digit integer string representation.

The reason your for loop isn't working is that you are iterating until you reach 8 - paramDecString.Length but that length keeps changing as you append 0s. It would work if you stored the value off first:

int numZeroes = (8-parmDecString.Length); 
for (int l=0; l < numZeroes; l++)
{
    parmDecString = "0" + parmDecString;
}

Also, string appending like that is expensive. Consider using StringBuilder instead as it doesn't create a new string every time you append to it.

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

1 Comment

Thanks. I'm new to C#, so I had no idea I could even use the 8-digit integer string representation. I changed the code to use that and its working exactly as expected. This is greatly appreciated... I'll store this away so I don't make the same stupid mistake next time.
2

parmDecString.Length increases at every loop, try to assign it to a variable before beginning the iteration

Comments

2

So you screwed up your loop by changing the bounds of the loop from within the loop... but really the loop wasn't necessary in the first place:

"123".PadLeft(8,'0') //ftw

Comments

0

Change:

for (int l=0; l < (8-parmDecString.Length); l++)

with:

int limit = 8-parmDecString.Length;
for (int l=0; l < (OriginalLength); l++)

That way changing length of string will not affect your loop.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.