Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Packing floats and reversing endian

by YuckFoo (Abbot)
on Jun 06, 2003 at 17:42 UTC ( [id://263790]=perlquestion: print w/replies, xml ) Need Help??

YuckFoo has asked for the wisdom of the Perl Monks concerning the following question:

I need to write a float in big-endian format on a little-endian machine. The only way I found to do it is to pack the number into float format, rip apart the bytes, reverse them, and repack them.

This works fine, but I'm little dizzy from hoop-jumping. Is there a shorter way to get there? Here is my example, in baby Perl to be clear about the steps. Please note: I'm not looking for denser code, I know I can use map to eliminate temporary variables. I'm looking for a better algorithm.

PackFoo

#!/usr/bin/perl use strict; my ($num, $str, @bytes); $num = -1.18024688796416e+29; $str = pack('f', $num); showstring('native', $str); @bytes = split('', $str); @bytes = reverse(@bytes); $str = join('', @bytes); $str = pack('a4', $str); showstring('alien ', $str); #----------------------------------------------------------- sub showstring { my ($label, $str) = @_; my @bytes = unpack('H2H2H2H2', $str); print "$label 0x", join("", @bytes), "\n"; }

Replies are listed 'Best First'.
Re: Packing floats and reversing endian
by Zaxo (Archbishop) on Jun 06, 2003 at 17:50 UTC

    You can reverse byte order with reverse in scalar context: $str = reverse $str; which will save you the split, temp array and join.

    After Compline,
    Zaxo

      Thanks Zaxo,

      I knew I was trying to hard. I forgot about using reverse on scalars. Just what I was looking for, and fast! Thanks,

      YuckFoo

Re: Packing floats and reversing endian
by BrowserUk (Patriarch) on Jun 06, 2003 at 19:12 UTC

    TIMTOWTDI:)

    print unpack'H2H2H2H2', pack'f', -1.180246887964 +16e+29 de ad be ef print unpack'H2H2H2H2', pack 'N', unpack 'V', pack'f', -1.180246887964 +16e+29 ef be ad de

    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "When I'm working on a problem, I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong." -Richard Buckminster Fuller


Re: Packing floats and reversing endian
by rir (Vicar) on Jun 06, 2003 at 18:35 UTC
    Somehow, YuckFoo, it seems appropriate that you would have endian problems.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://263790]
Approved by crouchingpenguin
Front-paged by broquaint
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (9)
As of 2024-03-28 23:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found