没脾气2x:
C# 问题,怎样让打包的字节顺序逆序
[阅读: 648] 2007-03-30 03:07:52
我想让下面程序里 magic、minor_verision、major_version 是按字位高位在前的……
现在读到的是 0xBEBAFECA
我想要 0xCAFEBABE
[CODE=C#]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
struct CLASS_FILE_HEADER
{
// 识别Class文件格式,具体值为0xCAFEBABE,
public UInt32 magic;
// Class文件格式副版本号
public UInt16 minor_version;
// Class文件格式主版本号
public UInt16 major_version;
}
class Program
{
static object BytesToStruct(byte[] bytes, Type structType)
{
int size = Marshal.SizeOf(structType);
IntPtr buffer = Marshal.AllocHGlobal(size);
try
{
Marshal.Copy(bytes, 0, buffer, size);
return Marshal.PtrToStructure(buffer, structType);
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}
static object ReadStruct(BinaryReader reader, Type structType)
{
int size = Marshal.SizeOf(structType);
byte[] bytes = new byte[size];
reader.Read(bytes, 0, size);
return BytesToStruct(bytes, structType);
}
static private void ReadFile(string filename)
{
Stream fs = File.Open(filename, FileMode.Open);
BinaryReader reader = new BinaryReader(fs);
CLASS_FILE_HEADER header;
header = (CLASS_FILE_HEADER)ReadStruct(reader, typeof(CLASS_FILE_HEADER));
Console.WriteLine("File: {0}", filename);
Console.WriteLine();
Console.WriteLine("
");
Console.WriteLine(" MAGIC: 0x{0:X8}", header.magic);
Console.WriteLine(" MAJOR_VERSION: 0x{0:X4}", header.major_version);
Console.WriteLine(" MINOR_VERSION: 0x{0:X4}", header.minor_version);
fs.Close();
}
}
[/CODE] Notemper2x 3.1 ( ̄ε( ̄#)
没脾气2x 之 个人综合篇:
http://notemper2x.cndev.org/
我的 panoramio 相册:
http://panoramio.com/user/zhaixudong
我的 flickr相册:
http://www.flickr.com/photos/notemper2x/
QQ号20250出售,售价400,000元整(5位、皇冠80级、VIP7)