I have the following code in Java:
public static byte[] hex(String hex) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int nexti = 0;
int nextb = 0;
boolean highoc = true;
outer:
while (true)
{
int number = -1;
while (number == -1) {
if (nexti == hex.length()) {
break outer;
}
char chr = hex.charAt(nexti);
if ((chr >= '0') && (chr <= '9'))
number = chr - '0';
else if ((chr >= 'a') && (chr <= 'f'))
number = chr - 'a' + 10;
else if ((chr >= 'A') && (chr <= 'F'))
number = chr - 'A' + 10;
else {
number = -1;
}
nexti++;
}
if (highoc) {
nextb = number << 4;
highoc = false;
} else {
nextb |= number;
highoc = true;
baos.write(nextb);
}
}
label161: return baos.toByteArray();
}
I'm trying to convert it to C#, and failing, because MemoryStream is the only option, and I don't have a buffer.
This is what I have now:
public static byte[] fromString(string hex)
{
MemoryStream baos = new MemoryStream();
int nexti = 0;
int nextb = 0;
bool highoc = true;
for (; ; )
{
int number = -1;
while (number == -1)
{
if (nexti == hex.Length)
{
goto END;
}
char chr = hex.ToCharArray()[nexti];
if (chr >= '0' && chr <= '9')
{
number = chr - '0';
}
else if (chr >= 'a' && chr <= 'f')
{
number = chr - 'a' + 10;
}
else if (chr >= 'A' && chr <= 'F')
{
number = chr - 'A' + 10;
}
else
{
number = -1;
}
nexti++;
}
if (highoc)
{
nextb = number << 4;
highoc = false;
}
else
{
nextb |= number;
highoc = true;
baos.Write(nextb);
}
}
END:
return baos.toByteArray();
}
What else can I do to make it work like the way in Java?.. Thanks.