2014-08-29 43 views
-1

我有一個持有字符串"02100030000000000000000000D5010008D501000804"一個變量,我字節分離使用強制整數是兩個數字 - VB

For i As Integer = 1 To (stringReader.Length - 1) Step 2 
       'Get the successive 2-character substrings, parse as bytes and add to total 
       Dim b As Byte = Byte.Parse(stringReader.Substring(i, 2), NumberStyles.AllowHexSpecifier) 
       sum = sum + CInt(b) 

      Next  

我將字符串直接integers.eg字符串:(字符串「10」到Integer10和)。這工作正常。但每當我將字符串「02」轉換爲Integer時,我只得到整數(2),而我需要整數(02)。我該如何繼續?

我的代碼是:

stringReader = fileReader.ReadLine()  
byt = stringReader(1) + stringReader(2)  

stringreader包含有類似"100030000000000000000000D5010008D501000804"

字節分離

For i As Integer = 1 To (stringReader.Length - 1) Step 2 
       'Get the successive 2-character substrings, parse as bytes and add to total 
       Dim b As Byte = Byte.Parse(stringReader.Substring(i, 2), NumberStyles.AllowHexSpecifier) 
       sum = sum + CInt(b) 

      Next 
+5

當存儲整數有2和02 – 2014-08-29 12:40:45

+0

沒有什麼區別你可以試試這個: - X .ToString(「D2」) – 2014-08-29 12:41:06

+0

如果是3位數字會怎麼樣?你想拋出驗證異常嗎?另外,負面價值呢?你期望「-00」是一個有效的價值嗎? – Neolisk 2014-08-29 12:42:09

回答

5

您可以使用

number.ToString("D2") 

其中number是一個整數類型,如System.Int32Integer)。

延伸閱讀:Standard Numeric Format Strings: The Decimal ("D") Format Specifier

如果你有String,而不是你也可以使用String.PadLeft

"2".PadLeft(2, "0"c) ' -> "02" 
+0

與整數可能相同嗎? – 2014-08-29 12:47:57

+0

@LakshmiNarasimhanRavichandra:當然,整數與'Int32'相同。 – 2014-08-29 12:51:38

+0

我的意思是問,是否可以填充一個整數,剩下零? – 2014-08-29 12:53:23