我有一个 DBase IV 数据库。每行都有一个带有 ASCII 编码字符串的备注字段,该字符串包含两个序列化的 borland c++ 结构。我可以使用 OleDb 提取数据,使用 ASCIIEncoding 类将其重新编码为 ascii,使用 BinaryReader 将其转换为字节,然后使用 Marshal.PtrToStructure 将其转换为我的 C# 结构。我得到的数据是正确的,但是当它被转换到 c# 时,数据库中任何大的浮点数都是完全错误的。例如,将 1149.00 的值转换为 764.9844,但将 64.00 之类的值转换为精细。我可以发布一些代码和结构,但我想我一开始会尽量保持简短。我知道浮点数最多只能精确到 7 位,但我很困惑为什么我会看到这个,因为这些值低于该限制。
编辑:
struct cplusplusstruct // from the c++ code
{
int Number;
float P;
float ZP;
float Hours;
int Month;
int Day;
int Year;
int Hour;
int Minute;
int Second;
ULONG UPCTime;
int B;
char Name[21];
float L;
float H;
float S;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct csharpstruct //The C# struct I created
{
public int Number;
public float Pr;
public float ZP;
public float Hours;
public int Month;
public int Day;
public int Year;
public int Hour;
public int Minute;
public int Second;
public UInt32 UPCTime;
public int B;
[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 21)]
public string Name;
public float L;
public float H;
public float S;
}
//OLE DB Connection and query ...
//Casting data to struct
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] blob = encoding.GetBytes(memoString);
MemoryStream memoryStream = new MemoryStream(blob);
BinaryReader binaryReader = new BinaryReader(memoryStream);
int dataSize = Marshal.SizeOf(typeof(csharpstruct));
GCHandle handle = GCHandle.Alloc(binaryReader.ReadBytes(dataSize), GCHandleType.Pinned);
csharpstruct data = (csharpstruct) Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(csharpstruct));
编辑:以下是读取数据的java代码,但没有使用任何强制转换。
org.xBaseJ.DBF dbf = new org.xBaseJ.DBF(dbPath);
org.xBaseJ.DBF dbf = new org.xBaseJ.DBF(dbPath);
MemoField m = (MemoField) dbf.getField("MEMOFIELD");
Charset charset = Charset.forName("US-ASCII");
CharsetDecoder decoder = charset.newDecoder();
ByteBuffer trendBytes = ByteBuffer.wrap(m.getBytes());
trendBytes.order(ByteOrder.LITTLE_ENDIAN);
trendBytes.getInt();
trendBytes.getFloat();