Clear questions and runnable code get the best and fastest answer |
|
PerlMonks |
comment on |
( [id://3333]=superdoc: print w/replies, xml ) | Need Help?? |
First of all I'd like to thank everyone for their contribution! I have realised, that my example and maybe question is unclear and confusing (e.g. regarding endian-ness), sorry about that! Let me try to rephrase my question: I'm looking to split any value/number consisting of x-amount of bytes into single bytes printed in hex and separated by space. So basically I just would like to print a "long" like 200'000 differently: 00 03 0d 40. I don't want to omit any leading zeros in any way, a "long" with 4 bytes should still consist of 4 separates bytes even if 3 would suffice as in my example with 200'000. My example with 200 is wrong as it can be represented by 1 byte (c8) and doesn't need a leading zero, sorry :-(
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
|
|