简体   繁体   中英

Receiving a HEX number and turning into an INT or STRING

I'm sending data from an ATmega in the form of 16 bit (2 bytes). I have a serial component in Delphi which receives the data.

  • If I send a String (eg 'FF' ), I get the data added to my Memo component. All fine.
  • However, if I send the raw hex $FF , I get a receive data blink saying "data received" but nothing is added to the Memo component's lines. I'm not sure how to convert this data into an Integer or String, something I can use.

A solution would be good but an explanation on how Delphi sees String , Char , etc. would be nice. Thanks.

When you receive data, you can cast them to bytes (if needed) and tranform into hex representation.

For example, if you get AnsiString :

  AnsiS := Comport.ReadAnsiString; //your reading here
  for i := 1 to Length(AnsiS) do
     Memo1.Lines.Add(IntToHex(Ord(AnsiS[i]), 2));

When your ATMega sends the string "FF", it sends two characters ("F" and "F"), each encoded to their ASCII code decimal 70. When your Delphi program receives these two bytes (d70 and d70) it converts those ASCII codes to characters "F" and "F" and adds them to the memo.

When your ATMega sends the hex value FF ($FF as they are represented in Delphi code), it sends one byte with decimal value 255. When your Delphi program receives this one byte (d255) it attempts to convert it to a character but doesn't find a printable character representation for this code. Therefore nothing is added to the memo. Or, maybe your receiving code is filtering out this and possibly other values too.

It's not clear exactly what kind of solution you are looking for, but you can convert the byte value (d255) to hex or decimal representation with function IntToHex(Value: Integer; Digits: Integer): string; or System.SysUtils.Format(const Format: string; const Args: array of const): string; or use it as a byte value in your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM