Hex encoding is very inefficient to handle because it's a non-contiguous part of the ASCII table. I usually use "cavcode"(*), because that's easy to implement in most programming languages, including in C for stuff like Arduinos. And of course it works very well with framing bytes.
sub frame2packet { my @frame = @_; my $packet = ''; foreach my $byte (@frame) { my $lowbyte = ($byte & 0x0f) + 65; my $highbyte = ($byte >> 4) + 65; $packet .= chr($highbyte); $packet .= chr($lowbyte); } return $packet; } sub packet2frame { my $packet = shift; my @chars = split//, $packet; my @frame = (); # Decode to bytes while(@chars) { my $high = shift @chars; my $low = shift @chars; my $val = ((ord($high) - 65) << 4) + (ord($low) - 65); push @frame, $val; } return @frame; }
Writing, for example, the counterpart encoder for Arduino is also quite easy. No need for a lookup table and stuff, this can be done with very low RAM usage:
highbyte = 0x02; Serial.write(highbyte); for(inoffs = 0; inoffs < PKT_LEN; inoffs++) { intmpbyte = inpacket[inoffs]; highbyte = ((intmpbyte >> 4) & 0x0f) + 65; lowbyte = (intmpbyte & 0x0f) + 65; Serial.write(highbyte); Serial.write(lowbyte); } highbyte = 0x03; Serial.write(highbyte);
(*) cavcode stands for "cavac encode". Yes, named it after myself, and nobody can stop me.
In reply to Re^2: Help adding STX and ETX to data string in Perl
by cavac
in thread Help adding STX and ETX to data string in Perl
by CuriousMark
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |