Bitcoin blockchain parser c# snippet to vb - vb.net

I am trying to get this snippet to vb but keep getting errors in the ide
var header = new byte[8];
int index = 0;
var magic_signature = ((uint)header[index++] << 0) | ((uint)header[index++] << 8) | ((uint)header[index++] << 16) | ((uint)header[index++] << 24);
I tried an online coverter and got this (which produces errors)
Dim magic_signature = (CUInt(header(Math.Max(Threading.Interlocked.Increment(index), index - 1))) << 0) Or (CUInt(header(Math.Max(Threading.Interlocked.Increment(index), index - 1))) << 8) Or (CUInt(header(Math.Max(Threading.Interlocked.Increment(index), index - 1))) << 16) Or (CUInt(header(Math.Max(Threading.Interlocked.Increment(index), index - 1))) << 24)
The header variable is filled after declaration.
Could someone help me convert the above to vb.net?
EDIT:
Populating header via reading a stream
Dim header = New Byte(8) {}
If stream.Read(header, 0, 8) < 8 Then
Throw New ApplicationException("Incomplete data.")
End If

As Mike_OBrien has pointed out, VB doesn't have a built-in ++ - but we can fake one easily enough:
Function PostIncr(ByRef x As Integer) As Integer
' PostIncr(i) works like i++
Dim x0 As Integer = x : x += 1 : Return x0
End Function
After that, conversion is straightforward:
Dim header(7) As Byte
' Make believe this is a stream.Read
Array.Copy({CByte(1), CByte(2), CByte(3), CByte(4)},
header, 4)
Dim index As Integer = 0
Dim magic_signature = CUInt(header(PostIncr(index))) << 0 Or
CUInt(header(PostIncr(index))) << 8 Or
CUInt(header(PostIncr(index))) << 16 Or
CUInt(header(PostIncr(index))) << 24
And for fun:
Function PreIncr(ByRef x As Integer) As Integer
' PreIncr(i) works like ++i
x += 1 : Return x
End Function

I believe David Wilson is on the right path but as rskar pointed out the Index + 1 portion does not produce the same results as index++ would in c#. The easiest way to get the behavior from c# would be to break the single command into multiple commands and store the results in temp variables, incrementing Index between each step and then evaluating the temp variables at the end. This would result in a lot more code however.
Ex:
Dim temp1 = (CUInt(header(Index)) << 0)
Index += 1
Dim temp2 = (CUInt(header(Index)) << 8)
Index += 1
Dim temp3 = (CUInt(header(Index)) << 16)
Index += 1
Dim magic_signature As UInteger = temp1 Or temp2 Or temp3 Or (CUInt(header(Index)) << 24)
Unfortunately to my knowledge there isn't anything in vb.net that behaves the same as the ++ operator in c#.

Related

Label a set of objects with (A->Z,AA->ZZ, AAA->ZZZ) in VBA

I have a set which has an unknown number of objects. I want to associate a label to each one of these objects. Instead of labeling each object with a number I want to label them with letters.
For example the first object would be labeled A the second B and so on.
When I get to Z, the next object would be labeled AA
AZ? then BA, BB, BC.
ZZ? then AAA, AAB, AAC and so on.
I'm working using Mapbasic (similar to VBA), but I can't seem to wrap my head around a dynamic solution. My solution assumes that there will be a max number of objects that the set may or may not exceed.
label = pos1 & pos2
Once pos2 reaches ASCII "Z" then pos1 will be "A" and pos2 will be "A". However, if there is another object after "ZZ" this will fail.
How do I overcome this static solution?
Basically what I needed was a Base 26 Counter. The function takes a parameter like "A" or "AAA" and determines the next letter in the sequence.
Function IncrementAlpha(ByVal alpha As String) As String
Dim N As Integer
Dim num As Integer
Dim str As String
Do While Len(alpha)
num = num * 26 + (Asc(alpha) - Asc("A") + 1)
alpha = Mid$(alpha, 2,1)
Loop
N = num + 1
Do While N > 0
str = Chr$(Asc("A") + (N - 1) Mod 26) & str
N = (N - 1) \ 26
Loop
IncrementAlpha = str
End Function
If we need to convert numbers to a "letter format" where:
1 = A
26 = Z
27 = AA
702 = ZZ
703 = AAA etc
...and it needs to be in Excel VBA, then we're in luck. Excel's columns are "numbered" the same way!
Function numToLetters(num As Integer) As String
numToLetters = Split(Cells(1, num).Address(, 0), "$")(0)
End Function
Pass this function a number between 1 and 16384 and it will return a string between A and XFD.
Edit:
I guess I misread; you're not using Excel. If you're using VBA you should still be able to do this will the help of an reference to an Excel Object Library.
This should get you going in terms of the logic. Haven't tested it completely, but you should be able to work from here.
Public Function GenerateLabel(ByVal Number As Long) As String
Const TOKENS As String = "ZABCDEFGHIJKLMNOPQRSTUVWXY"
Dim i As Long
Dim j As Long
Dim Prev As String
j = 1
Prev = ""
Do While Number > 0
i = (Number Mod 26) + 1
GenerateLabel = Prev & Mid(TOKENS, i, 1)
Number = Number - 26
If j > 0 Then Prev = Mid(TOKENS, j + 1, 1)
j = j + Abs(Number Mod 26 = 0)
Loop
End Function

vb.net arithmetic operation resulted in an overflow in decryption

I am working on new decryption functions for password recovery tools. I tried code in c++ and worked:
void poco_pwd(u_char *pwd, int type) {
int len,
tmp;
u_char *out;
short azz;
if(type) azz = 0x2537; // encrypt message
else azz = 0x2a9a; // other passwords
len = strlen(pwd) >> 1;
out = pwd;
while(len--) {
sscanf(pwd, "%02X", &tmp);
pwd += 2;
*out++ = tmp ^ (azz >> 8);
azz = ((tmp + azz) * 0x8141) + 0x3171;
}
*out = 0;
}
I tried to convert this code to vb.net and c# but it throws arithmetic overflow operation. This functions new value is put to "azz" variable. "azz" is a short variable but this these values are very high. Strange is that it works in c++.
I converted this code to vb.net:
Dim encpass As String = "1EF66D8BD3C32476CEC8CF"
Dim encpassByte As Byte() = Encoding.UTF8.GetBytes(HexToString(encpass))
Dim azz As Integer = &H2A9A
Dim len As Integer = encpassByte.Length >> 1
Dim storage(len) As Char
For i = 0 To len
storage(i) = (ChrW(encpassByte(i) Xor (azz >> 8)))
azz = ((encpassByte(i) + azz) * &H8141) + &H3171 //Error: arithmetic operation resulted in an overflow.
Next
Console.WriteLine(storage.ToString)
Console.ReadKey()
Hex to string function:
Function HexToString(ByVal hex As String) As String
Dim text As New System.Text.StringBuilder(hex.Length \ 2)
For i As Integer = 0 To hex.Length - 2 Step 2
text.Append(Chr(Convert.ToByte(hex.Substring(i, 2), 16)))
Next
Return text.ToString
End Function
This code throws this error: arithmetic operation resulted in an overflow.

Performance loss in VB.net equivalent of light weight conversion from hex to byte

I have read through the answers here https://stackoverflow.com/a/14332574/44080
I've also tried to produce equivalent VB.net code:
Option Strict ON
Public Function ParseHex(hexString As String) As Byte()
If (hexString.Length And 1) <> 0 Then
Throw New ArgumentException("Input must have even number of characters")
End If
Dim length As Integer = hexString.Length \ 2
Dim ret(length - 1) As Byte
Dim i As Integer = 0
Dim j As Integer = 0
Do While i < length
Dim high As Integer = ParseNybble(hexString.Chars(j))
j += 1
Dim low As Integer = ParseNybble(hexString.Chars(j))
j += 1
ret(i) = CByte((high << 4) Or low)
i += 1
Loop
Return ret
End Function
Private Function ParseNybble(c As Char) As Integer
If c >= "0"C AndAlso c <= "9"C Then
Return c - "0"C
End If
c = ChrW(c And Not &H20)
If c >= "A"C AndAlso c <= "F"C Then
Return c - ("A"C - 10)
End If
Throw New ArgumentException("Invalid nybble: " & c)
End Function
Can we remove the compile errors in ParseNybble without introducing data conversions?
Return c - "0"c Operator '-' is not defined for types 'Char' and 'Char'
c = ChrW(c And Not &H20) Operator 'And' is not defined for types 'Char' and 'Integer'
As it stands, no.
However, you could change ParseNybble to take an integer and pass AscW(hexString.Chars(j)) to it, so that the data conversion takes place outside of ParseNybble.
This solution is much much faster than all the alternative i have tried. And it avoids any ParseNybble lookup.
Function hex2byte(s As String) As Byte()
Dim l = s.Length \ 2
Dim hi, lo As Integer
Dim b(l - 1) As Byte
For i = 0 To l - 1
hi = AscW(s(i + i))
lo = AscW(s(i + i + 1))
hi = (hi And 15) + ((hi And 64) >> 6) * 9
lo = (lo And 15) + ((lo And 64) >> 6) * 9
b(i) = CByte((hi << 4) Or lo)
Next
Return b
End Function

Splitting a String into Pairs

How would I go on splitting a string into pairs of letter in VB?
for example: abcdefgh
split into: ab cd ef gh
I'll throw my hat in the ring:
Dim test As String = "abcdefgh"
Dim results As New List(Of String)
For i As Integer = 0 To test.Length - 1 Step 2
If i + 1 < test.Length Then
results.Add(test.Substring(i, 2))
Else
results.Add(test.Substring(i))
End If
Next
MessageBox.Show(String.Join(" ", results.ToArray))
The following allows for odd length strings. If the string is zero-length, I'm not sure what you'd want to do, you'll want to address that case.
Dim src As String = "abcdef"
Dim size As Integer
If src.Length > 0 Then
If src.Length Mod 2 = 0 Then
size = (src.Length / 2) - 1
Else
size = ((src.Length + 1) / 2) - 1
End If
Dim result(size) As String
For i = 0 To src.Length - 1 Step 2
If i = src.Length - 1 Then
result(i / 2) = src.Substring(i, 1)
Else
result(i / 2) = src.Substring(i, 2)
End If
Next
End If
In C# you would do like this:
Dictionary<String, String> Split(String input)
{
if (input.Count % 2 == 0)
{
Dictionary<string, string> Pairs = new Dictionary( );
for (int L = 0, R = 1; L < input.Count && R <= input.Count; ++L, ++R)
{
Char
Left = input[L],
Right = input[R];
Pairs.Add(
Left.ToString(),
Right.ToString());
}
}
else
{
throw new NotEvenException( );
}
return Pairs( );
}
void Main()
{
var Pairs = Split("ABCDEFGH");
foreach(string Key in Split("ABCDEFGH"))
{
Console.Write("{0}{1}\n", Key, Pairs[Key]);
}
}
/*
Output:
AB
CD
EF
GH
*/
Now, I know what you think: This isn't what I want! But I say: It is actually, at least partly.
Since I presume you're working in VB.net, the basic structure of what you want performed is outlined in the short snippet above.
For example: The method Count (of the object String) exists in both C# and in VB.
Hope it helps a bit at least!

Project Eulers problem 16 in visual basic. Sum of digits in the number 2^1000

Project Euler's problem 16:
2^(15) = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 2^(1000)?
I have been trying to do this problem for a few days now and i just can't figure out how to get vb.net 2008 to recognize anywhere near that large a number. I have seen in other posts that some software like java has the integer type BigNumber or BigInteger but i cant find anything like that in visual basic. I'm running into this problem a lot using Visual Basic. I also can't seem to find any of the standard upper level math features in visual basic such as factorials and a few others that i can't remember but couldn't find under the math feature. any suggestions? (Sorry let me rephrase, any suggestions on how to do this stuff without switching to a different programming language.)
here's the function I wrote, it's not so difficult to do your own implementation of a BigInteger purely for this purpose (very difficult to make it efficient and versatile however, but that's what libraries are for)
Public Shared Function Problem16(ByVal power As Integer) As String
Dim digits As Integer = CInt(Int(power * Log10(2)))
Dim number(digits) As Byte
number(digits) = 1
For i As Integer = 1 To power
Dim carry As Byte = 0
For j As Integer = digits To 0 Step -1
number(j) <<= 1
number(j) += carry
If number(j) > 9 Then
carry = number(j) \ CByte(10)
number(j) -= CByte(10)
Else
carry = 0
End If
Next
Next
Dim result As Integer
For i As Integer = 0 To digits
result += number(i)
Next
Return result.ToString
End Function
There are several BigInteger libraries that are freely available which you can use.
http://msdn.microsoft.com/en-us/magazine/cc163696.aspx
http://www.codeproject.com/KB/cs/biginteger.aspx?df=100&forumid=4524&exp=0&fr=26
In this case the limitations are not necessarily the language. Visual Basic, outside of basic math operations, largely depends on the BCL for functionality. This is true of most languages which run on the CLR (including C#). In most cases though, there are libraries available which you can use to augment the functionality of the framework.
I haven't tried it but there seems to be a Big Integer construct for Visual Basic.
public static void main(String[] args) {
int m = 2, ci = 1, n = 1000, i;
int[] arr = new int[n + 1];
arr[1] = 1;
for (i = 1; i <= n; i++) {
int carry = 0;
for (int j = 1; j <= ci; j++) {
arr[j] = arr[j] * m + carry;
carry = arr[j] / 10;
arr[j] = arr[j] % 10;
}
if (carry > 0) {
while (carry > 0) {
ci++;
arr[ci] = carry % 10;
carry = carry / 10;
}
}
}
int sum = 0;
System.out.println(ci + "\n \n ");
for (int j = ci; j > 0; j--) {
System.out.print(arr[j]);
sum = sum + arr[j];
}
System.out.println("\n \n " + sum);
}
Answer:
Number of digits in 2^1000: 302
2^1000=
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
sum of the digits: 1366