http://www.perlmonks.org?node_id=676792


in reply to Re: Hex Question(s)
in thread Hex Question(s)

That's the question I guess - is there any? Doesn't a hex value normally begin with 0x? And it isn't it normally specified without quotes?
$hex = 0x1234; #prints 4660
as opposed to
$hex = '0x1234'; #prints 0x1234

Replies are listed 'Best First'.
Re^3: Hex Question(s)
by Corion (Patriarch) on Mar 27, 2008 at 16:47 UTC

    What I was aiming at is, that Perl makes no distinction between the base of numbers. You may specify a number in hexadecimal notation, that is, starting with 0x, or as a plain integer, that is, in decimal notation, or in octal notation, starting with a leading zero. Internally, Perl will treat all these as numbers, because they get converted to the Perl-internal representation for numbers.

    If you have a string and you want to perform arithmetic operations on it, the easiest way to do that is if the string looks_like_number, that is, is in decimal notation (at least for this discussion). Otherwise, you have to convert from the notation you have to the decimal notation. For example, the functions hex and oct do that.

    But maybe, we can just leave the plane of metaphysical discussions of the representation of numbers, and the numbers themselves (and whether numbers exist without representation) and you tell us what problem you're trying to solve?

      Okay, that makes sense.

      At this point it probably would make sense to expand on the problem that I'm trying to solve. Basically, what I need to do is take my hex string, split it into pairs and prepend those pairs with \x. Then I concatenate them all together, pack them and stick them into a DHCP packet. It looks something like this:
      $theInt = 1501299200; $theHex = sprintf("%lx", $theInt); $hexPairs = split(/(\w{1,2})/, $theHex); while $val (@hexPairs) { if (!$thisPair eq "" ) { $finalHex .= "\x".$thisPair; } } $bytes .= pack("C/a*", $finalHex);
      The resulting hex stuff should look like this: \x59\x7c\x02\x00 and if I replace $finalHex above with "\x59\x7c\x02\x00" then my code works fine (but that's not an acceptable solution because the initial integer isn't always going to be 1501299200).

      I appreciate that this may not make a hell of a lot of sense or that it may be diffcult to follow what I'm trying to do so I am grateful for any help that you can give me.

      Maybe I'm just overcomplicating things?

        Well, your description is quite roundabout for the effect you want to achieve. Basically, you want to build a byte string consisting of arbitrary characters.

        For building such stuff, Perl has pack, which builds a string out of various kinds of values.