我有一個J1939 CAN原始字符串以下列格式:字符串轉換爲字節
CAN:0B00FEE99CF002000CEF02000B00FEE81A9A9F60FFFFB8570B00FEE042522500425225000B00FEE5E0530100C89F0400
此字符串包含被分成3份幾個CAN消息,例如
0B 00FEE99 CF002000CEF0200
1)以字節爲單位PGN數據長度0B
2)PGN數(長度3個字節)0FEE99
3)PGN數據CF002000CEF0200
目前,我使用子字符串來分析3部分,但我沒有得到正確的值。我想我可能會犯一個錯誤,因爲我沒有將字符串轉換爲字節數組。 這是我的代碼的一部分:
int CANStrLength = 24;
int CANIndex = CANDataIndex(rawDataElements);
int CANStrIndex = rawDataElements[CANIndex].IndexOf("CAN:");
string CANmessage = rawDataElements[CANIndex].Substring(CANStrIndex + 4).Split(',').First();
Console.WriteLine("\nIn rawDataElements[{0}]: {1}\nLength of CAN data: {2}", CANIndex, CANmessage, CANmessage.Length);
int numberOfCANMessages = CANmessage.Length/CANStrLength;
Console.WriteLine("There are {0} CAN messages", numberOfCANMessages);
List<string> CANMessages = SplitIntoParts(CANmessage, CANStrLength);
for (int i = 0; i < numberOfCANMessages; i++)
{
int pgnDataLength = Convert.ToInt32(CANMessages[i].Substring(0, 2), 16);
int pgnNumber = Convert.ToInt32(CANMessages[i].Substring(2, 6), 16);
long CANData = Convert.ToInt64(CANMessages[i].Substring(8), 16);
Console.WriteLine();
Console.WriteLine(CANMessages[i]);
switch (pgnNumber)
{
// fuel consumption */
case 65257:
string totalFuelUsedStr = CANMessages[i].Substring(8).Substring(8, 4);
double totalFuelUsed = Convert.ToInt32(totalFuelUsedStr, 16) * 0.5;
Console.WriteLine("Total Fuel Used: {0}L, {1}gal", totalFuelUsed, (int)(totalFuelUsed* 0.26));
break;
是的,它可能更容易轉換爲字節數組(請參閱anwer bwlow),而且您的代碼也應該可以工作。哪些值是錯誤的?用調試器或程序輸出你正在轉換的字符串的部分。也許這只是曲解。在你的例子中,你說'PGN編號3字節'(這將是字符串中的6個字符),但字符串「00FEE99」是七個字符長。 –
@ H.G.Sandhagen - PGN是6個字符長'0FEE99' –
@ H.G.Sandhagen我錯了數據部分。 –