hexadecimal addition

K

king

suppose i have got a variable say
$reserved=D0020078
I want to do a hexadecimal addition of $reserved with 08h.

so the output should come as $output=D0020080.
How can i do this.

I didn't find any syntax in "sprintf" for this.
Because this is a hexadecimal addition.
How can i do this?
thanx
 
N

Nick of course

king said:
suppose i have got a variable say
$reserved=D0020078
I want to do a hexadecimal addition of $reserved with 08h.

so the output should come as $output=D0020080.
How can i do this.

I didn't find any syntax in "sprintf" for this.
Because this is a hexadecimal addition.
How can i do this?
thanx
perl -e '$reserved="D0020078"; printf "%08x\n", oct("0x$reserved") +
oct("0x08")'

Note - you need to quote the D0020078. If it had not started with an
alpha it would have barfed. use strict would also have pointed this
out.
 
B

Ben Morrow

Quoth "king said:
suppose i have got a variable say
$reserved=D0020078

Nope, you haven't. That is, unless you aren't using 'strict', in which
case you don't have a number, you have an unquoted string. These are Bad.

You probably meant

my $reserved = 0xD0020078;
I want to do a hexadecimal addition of $reserved with 08h.

There is no such thing as 'hexadecimal addition'. Addition is addition;
the question of base only applies to reading and writing numbers.

You tell Perl a number written in your source file is hex by preceding
it with '0x', as I showed you above. Please read perldoc perldata.

You tell Perl to interpret a string as a hex number with the hex
function. Please read perldoc -f hex. (While you're there, you'd do well
to read all of perldoc perlfunc.)

You tell Perl to convert a number to hex representation by using sprintf
with the %x or %X formats. You seem to have already read perldoc -f
sprintf: you may want to read it again with a proper understanding of
the difference between a number and the way it is written.

So the answer you are looking for is probably

my $reserved = 0xD0020078;
print sprintf "%X", $reserved + 0x08;

Please read at least some of the Perl documentation, or a good
introductory book, before trying random things on your own.

Ben
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,176
Messages
2,570,950
Members
47,503
Latest member
supremedee

Latest Threads

Top