View Full Version : rounding up hex numbers
buzzwogger
03-01-2007, 02:56 PM
Is there any method available in perl to round up a hex number? For example "0109" value is counted up to "010a". Thanks in advance.
buzzwogger
03-01-2007, 04:29 PM
I can't seem to see any method so I am trying the following, so far it is not working but I think I am assigning and substituting the last char incorrectly so any help would be brilliant
for(my $x= 0; $x<= $tx_bits; $x++)
{
#Is last char 9
if ($ts_number[$x]=~ m/9$/)
{
$ts_roundup[$x] = $ts_number[$x];
#roundup --> Substitute 9 for a
$ts_roundup[$x]=~ s/a$/;
print "ts round up :" . $ts_roundup[$x] . "\n";
}
$ts_dec[$x]=hex($ts_roundup[$x]);
}
ralph l mayo
03-01-2007, 04:43 PM
I'm not sure how this rounding scheme is supposed to work. In your code it looks like you just want to replace trailing 9 with a? in that case:
my $hex = 0x0109;
$hex += 1 if $hex&0x09 == 0x09;
printf '0x0%x', $hex;
my $hex_string = '0x0109';
$hex_string =~ s/9\z/a/xms;
print $hex_string;
If you're actually rounding by some scheme, please explain in a little more detail. Are you assuming trailing characters are after the decimal point, or do you want to round to multiples or powers of something?
buzzwogger
03-01-2007, 05:04 PM
Thanks for your help I was rounding up hex numbers so an example was
my $hex_string = '0x0109' --> roundup '0x010a', another example would be my $hex_string = '0x0101' --> roundup '0x0102', so I will now loop through and check last char and substitute it with the next significant char...
I changed the line
$ts_roundup[$x]=~ s/a$/;
to
$ts_roundup[$x]=~ s/9$/a/;
And that sorted out my problem
ralph l mayo
03-01-2007, 07:34 PM
Where I come from they call that "addition"
vBulletin® v3.8.2, Copyright ©2000-2010, Jelsoft Enterprises Ltd.