Thread Rechnen mit Hex (2 answers)
Opened by Gast at 2007-08-18 18:14

Ronnie
 2007-08-19 13:13
#98377 #98377
User since
2003-08-14
2022 Artikel
BenutzerIn
[default_avatar]
Du könntest aus eine eigene Klasse für Hex-Zahlen definieren:
Code (perl): (dl )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#!/usr/bin/perl

use strict;
use warnings;

use Data::Dumper;

package HexNumber;

use Moose;
use overload    '+'     => \&add,
                '""'    => \&to_s;

has '_value'     =>  ( is => 'rw' );

sub set {
    my $self = shift;
    my $val = shift;
    return unless $val =~ /^[\da-fA-F]+$/;
    $self->_value(hex($val));
}

sub add {
    my $self = shift;
    my $other = shift;
    return (blessed $other) ?
        HexNumber->new(_value => $other->_value + $self->_value) :
        HexNumber->new(_value => $other + $self->_value) ;
}

sub to_s {
    my $self = shift;
    return sprintf '%x', $self->_value;
}

package main;

sub to ($) { shift } # just syntactic sugar

my $foo = HexNumber->new(_value => '44800'); # only dec-values directly
my $bar = HexNumber->new();

set $bar to 'fe'; # the same as $bar->set('fe');

my $buz = $foo + $bar;
print $buz, "\n" x 2;
print Dumper \$buz;

View full thread Rechnen mit Hex