2019. 10. 1. 19:37ㆍ기타
hex 파일을 열어서 HexData 변수에 할당
byte[] HexData = null;
enum DATA_TYPE
{
HEX_FILE_DATA = 0x00,
HEX_FILE_EOF = 0x01,
HEX_FILE_EXTENDED_LINEAR_ADDRESS = 0x04,
HEX_FILE_MAX
};
private void btnFileOpen_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
if (dlg.ShowDialog() == DialogResult.OK)
{
string fileName = dlg.FileName;
//MessageBox.Show(fileName);
if (File.Exists(dlg.FileName))
{
lblHexFilePath.Text = dlg.FileName;
UInt32 recordLength;
UInt32 addressField = 0;
UInt32 recordType;
byte checksum;
byte calc_checksum;
UInt64 extendedAddress = 0;
string dataPayload;
//HexData = File.ReadAllBytes(dlg.FileName);
//string strFileData = File.ReadAllText(dlg.FileName);
List bin_data = new List();
Stream stream = dlg.OpenFile();
using (StreamReader reader = new StreamReader(stream))
{
bool hexFileEOF = false;
string strLine = reader.ReadLine();
while (hexFileEOF == false)
{
strLine = strLine.Trim();
if (strLine.Length > 0 && strLine[0] == ':')
{
recordLength = StringToHex(ref strLine, 1, 2);
addressField = StringToHex(ref strLine, 3, 4);
recordType = StringToHex(ref strLine, 7, 2);
dataPayload = strLine.Substring(9, (int)(recordLength * 2));
checksum = (byte)StringToHex(ref strLine, 1 + (recordLength * 2) + 8, 2);
calc_checksum = CalcCheckSum(ref strLine, 1, (recordLength + 4) * 2);
calc_checksum ^= 0xFF;
calc_checksum += 1;
if (checksum == calc_checksum)
{
switch((DATA_TYPE)recordType)
{
case DATA_TYPE.HEX_FILE_EXTENDED_LINEAR_ADDRESS:
extendedAddress = StringToHex(ref dataPayload, 0, (uint)dataPayload.Length);
break;
case DATA_TYPE.HEX_FILE_EOF:
hexFileEOF = true;
break;
case DATA_TYPE.HEX_FILE_DATA:
{
UInt64 totalAddress = (extendedAddress << 16) + addressField;
for (uint i=0; i< dataPayload.Length; i+=2)
{
bin_data.Add((byte)StringToHex(ref dataPayload, i, 2));
}
}
break;
default:
break;
}
}
}
strLine = reader.ReadLine();
}
}
if(bin_data.Count > 0 && extendedAddress != 0)
{
HexAddress = (UInt32)extendedAddress;
HexData = bin_data.ToArray();
}
}
}
}
private byte CalcCheckSum(ref String s, uint index, uint len)
{
byte checksum = 0;
byte data;
for(int i=0; i<len; i+=2)
{
data = (byte)StringToHex(ref s, (uint)(index + i), 2);
//checksum ^= data;
checksum += data;
}
return checksum;
}
private UInt32 StringToHex(ref String s, uint index, uint len)
{
UInt32 returnAddress = 0;
for(int i=0; i<len; ++i)
{
returnAddress *= 16;
byte c = (byte)s[(int)(index + i)];
if ((c >= 'A') && (c <= 'F'))
{
returnAddress += (UInt32)(10 + (c - 'A'));
}
else if ((c >= 'a') && (c <= 'f'))
{
returnAddress += (UInt32)(10 + (c - 'a'));
}
else
{
returnAddress += (UInt32)(c - '0');
}
}
return returnAddress;
}
'기타' 카테고리의 다른 글
버추얼 박스(VirtualBox)에 설치된 Ubuntu에 USB2Serial 데이터 송수신 (0) | 2020.01.09 |
---|---|
AWS 리눅스 서버 구축시 필요한 명령어 이것저것 (0) | 2020.01.01 |
[STM32F765ZI] 부트로더를 이용한 소프트웨어 업데이트 (0) | 2019.10.16 |
패킷 전송 프로그램 (0) | 2019.05.20 |
C# tab control에 winform 넣기 (1) | 2019.04.20 |