我正在转换一个将 BCD 数据转换为 ASCII 的 Java 类
我正在将其转换为 .Net BCD 转换器
以下是从 java 转换而来的,但它给出了错误的转换值,例如对于 123456789,它给出 123456153153
public static string GetStringFromBcd(int[] b)
{
StringBuilder buffer = new StringBuilder();
foreach (var t in b)
{
if ((t & 0x0000000F) == 0x0000000F && ((t >> 4) & 0x0000000F) == 0x0000000F)
{
break;
}
buffer.Append((t & 0x0000000F) + "");
if ((t & 0x000000F0) != 0x000000F0)
{
buffer.Append(((t >> 4) & 0x0000000F) + "");
}
}
}
可能是什么问题?
编辑:答案:
我得到了数据已被BCD编码的源程序。 我发现这个逻辑没有任何问题,然后我发现了函数的来源,其中数据从网络流转换为字符串,然后转换为字节/整数数组。 以下是代码
int bytesRead = tcpClient.Receive(message);//, 0, bytetoReadSize);
if (bytesRead == 0)
{
break;
//the client has disconnected from the server
}
//message has successfully been received
data += new ASCIIEncoding().GetString(message, 0, bytesRead);
问题是 ASCIIEncoding 不会转换许多编码字符,并给出 '?'63 而不是那些字符,当将 63 放入 BCD 转换逻辑时,它给出 153。
为了解决此错误,我修改了最后一行,而不是解码,我只是将接收到的字节转换为字符。
foreach (byte b in message)
{
data += ((char) b);
}
最佳答案
这是一个类似的 Question,它有几种不同的方式。
这里有一个 Site,它对您所面临的情况进行了非常详细的描述。
这应该不难,但是将它们处理为 int 会困难得多。
分区十进制 (BCD) 的转换非常简单,但如果从大型机获取已通过 ASCII 传输转换的文件,则必须小心。它仍然可以转换,但由于 FTP 期间将 ebcdic 转换为 ascii,字节值会发生变化。
如果你处理的是二进制文件,那就容易处理多了。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestZoned
{
class Program
{
public static String zoneToString(byte[] zoneBytes)
{
Encoding ascii = Encoding.ASCII;
Encoding ebcdic = Encoding.GetEncoding("IBM037");
byte[] asciiBytes = null;
String str = null;
int zoneLen = zoneBytes.Length;
int i = zoneLen - 1;
int b1 = zoneBytes[i];
b1 = (b1 & 0xf0) >> 4;
switch (b1)
{
case 13:
case 11:
zoneBytes[i] = (byte)(zoneBytes[i] | 0xf0);
asciiBytes = Encoding.Convert(ebcdic, ascii, zoneBytes);
str = "-" + ASCIIEncoding.ASCII.GetString(asciiBytes);
break;
default:
zoneBytes[i] = (byte)(zoneBytes[i] | 0xf0);
asciiBytes = Encoding.Convert(ebcdic, ascii, zoneBytes);
str = ASCIIEncoding.ASCII.GetString(asciiBytes);
break;
}
return (str);
}
static void Main(string[] args)
{
byte[] array = { 0xf0, 0xf0, 0xf1 }; // 001
byte[] pos = { 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9 }; // 123456789
byte[] neg = { 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xd9 }; // -123456789
Console.WriteLine("Converted: {0}", zoneToString(array));
Console.WriteLine("Converted: {0}", zoneToString(pos));
Console.WriteLine("Converted: {0}", zoneToString(neg));
}
}
}
关于c# - 将 BCD 转换代码从 Java 迁移到 .Net,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11666488/