Anyway, I would then use this code to create a function which takes any number of arguments and returns a string consisting of a series of single bytes represented in hex. The only thing I came up with is this:
#!/usr/bin/perl
sub number2hexString {
my $output;
my $packTemplate;
foreach my $i (@_) {
if ($i > 65535) {
$packTemplate = 'L>';
} elsif ($i > 255) {
$packTemplate = 'S>';
} else {
$packTemplate = 'C';
}
$output .= join(' ', unpack('(H2)*', pack($packTemplate, $i))).' ';
}
return $output;
}
print number2hexString(2,20,200,2000,20000,200000)."\n";
this results in:
$ ./test.pl 02 14 c8 07 d0 4e 20 00 03 0d 40 $
This works. However, I don't need perl to know the type of number it needs to convert. It shouldn't care whether it's a char, short, long, quad, signed or unsigned or whatever. It should just take each variable as a series of bytes and convert it to single bytes represented in hex. Basically I'm looking to replace the if/elsif/else part in the above sub.I'm hoping this clears things up!
Background: I'm using this to communicate via I2C (a slow serial hardware bus) between a Raspberry and an Arduino. As it is slow I do not want to waste unnecesseray bytes (otherwise sending everything as a quad or long would be an option). And as I'm handling the Arduino side as well I know which datatype I'm expecting based on the register and can then reassemble my series of bytes into single bytes, ints or longs etc. A sample transmission would be: master sends: 02 14 07 d0 which the slave (arduino) interprets as follows:
In reply to Re: Split any number into string of 8-bit hex values (=1 byte)
by drsweety
in thread Split any number into string of 8-bit hex values (=1 byte)
by drsweety
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |