2

I am using like this,

$a = "002c459f";
$b = $a%10000;
$c = int($a/10000); 
print $b;       #prints 0
print $c;       #prints 2

I want

$b=459f;

$c=002c;

Can anyone suggest how will I get this?

toolic
  • 57,801
  • 17
  • 75
  • 117
Alexx
  • 475
  • 2
  • 8

3 Answers3

3

If you had used warnings, you would have gotten a warning message indicating a problem.

Since your 8-bit input is already formatted as a simple hex string, you can just use substr:

use warnings;
use strict;

my $x = '002c459f';
my $y = substr $x, 0, 4;
my $z = substr $x, 4, 4;
print "z=$z, y=$y\n";

Output:

z=459f, y=002c

It is a good practice to also use strict. I changed your variable names since a and b are special variables in Perl.

toolic
  • 57,801
  • 17
  • 75
  • 117
2

You should always use use strict; use warnings;! It would have told you that 002c459f isn't a number. (It's the hex representation of a number.) As such, you can't use division before first converting it into a number. You also used the wrong divisor (10000 instead of 0x10000).

my $a_num = hex($a_hex);

my $b_num = $a_num % 0x10000;         # More common: my $b_num = $a_num & 0xFFFF;
my $c_num = int( $a_num / 0x10000 );  # More common: my $c_num = $a_num >> 16

my $b_hex = sprintf("%04x", $b_num);
my $c_hex = sprintf("%04x", $c_num);

But if you have exactly eight characters, you can use the following instead:

my ($c, $b) = unpack('a4 a4', $a);

Note: You should avoid using $a and $b as it may interfere with sort and some subs.

ikegami
  • 367,544
  • 15
  • 269
  • 518
1

Input data is a hex string, regular expression can be applied to split string by 4 characters into an array.

At this point you can use result as a strings, or you can use hex() to convert hex string representation into perl's internal digital representation.

use strict;
use warnings;
use feature 'say';

my $a = "002c459f";         # value is a string

my($b,$c) = $a =~ /([\da-f]{4})/gi;

say "0x$b 0x$c\tstrings";   # values are strings

$b = hex($b);               # convert to digit
$c = hex($c);               # convert to digit

printf "0x%04x 0x%04x\tdigits\n", $b, $c;

Output

0x002c 0x459f   strings
0x002c 0x459f   digits
Polar Bear
  • 6,762
  • 1
  • 5
  • 12