Have you read
perldoc -f hex?
The last line there points you thusly:
.... To present something as hex, look
into "printf", "sprintf", or "unpack".
Or, of course, you could write your own, but reading the docs may be easier. :-) | [reply] |
I do not understand your question. Your current script produces the following output:
1: 33
2: 45
3: 57
4: 69
5: 81
...
I modified your code so that it would print out the value of the $a variable in hexadecimal notation (with a "0x" prefix), using the Perl built-in function printf:
#!/usr/bin/env perl
use warnings;
use strict;
my $a=0x15;
for (my $i = 1; $i <= 100; $i++)
{
$a+=0x0C;
print "$i: ";
printf "0x%x\n", $a;
}
This is the new output:
1: 0x21
2: 0x2d
3: 0x39
4: 0x45
5: 0x51
...
If this is not the output you are looking for, please provide a small sample of your desired output.
Please also state a reason why you do not want to use printf. | [reply] [d/l] [select] |
| [reply] [d/l] |
"Calculating in hex" makes no sense. Hex is just a representation of a number, so it's only relevant when viewing the number. A hex string needs to a number in order to do calculations on it. (In the case of literals like 0x15, the Perl parser does that for you.) And a number needs to be converted to a string to display it on the console. (print converts numbers into a decimal strings. (s)printf '%X' converts numbers into a hex strings.)
| [reply] [d/l] [select] |
hi ww,
well, that's true :-)
this line: $a+=0x0C is not working, because it count decimal.
or am i mistaken ? | [reply] |
I'm not sure I understand that, but my guess is that you don't.
You code does spit out the appropriate decimal values...
- 33
- 45
- 57
- 69
- ...
and, as line 100, 1221
...so, as I understand your inital question and followup, your issue is presentation or formatting; not the arithmetic, nor any error in the syntax you've shown us (note, however, that your loop is not particularly perlish).
updateFollowing up on (well, preceding up on ???) toolic's suggestion with an example using pack/unpack:
for (my $i = 1; $i <= 20; $i++) {
$a+=0x0C;
$out = pack "c", $a;
$hex = unpack "H2", $out;
print "\t$i Now, \$a (as decimal) is:\t$a \tand as hex: 0x$hex\n";
}
And if this is indeed homework, the implicit suggestion of Fletch's comment may be "FGS, at least label it as such."
| [reply] [d/l] |
Thank you,
your last comment did help very well.
| [reply] |