Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Process set number of bytes at a time

Status
Not open for further replies.
Jun 3, 2007
84
US
Hello,

I was hoping someone could point me in the right direction/help me out with the following problem.

I have the following code shown below.

Code:
#!/usr/bin/perl
use strict;
use warnings;

my $input_string = 'test';
my $hexchars = '';

foreach my $chars (split(//,$input_string)) {
    $hexchars .= sprintf "%x", ord($chars);
}
print "$input_string\n";
print "$hexchars\n";

my $length = length $hexchars;
my $start = 0;
my $end = $start + $length;

print "length $length\n";
print "start_offset: $start\n";
print "end_offset: $end\n";

for ( $start = 0; $start < $length; $start ++ ) {
    print $start, "\n";
}

What I am trying to do is process the output of the $hexchars variable but doing so 4 bytes at a time until no more data is left in the $hexchars variable. I am trying to reverse/swap two bytes from the 4 bytes that I am processing at a time.

Example:
the string "test" which I have in the input variable gets converted to: 74657374 in HEX. Now what I am trying to do is grab 4 bytes so in this case 7465 and swap/reverse them so they show up as so 6574. Then continue on to the next 4 characters and do the same until the variable is empty.

Where I am having trouble is how to I process 4 characters at a time?

Thanks for the help in advance.
 
Here's one way:
Code:
$_ = 'AABBCCDD';
my $out = "";
while (/([\dA-F]{2})([\dA-F]{2})/ig) {
	$out .= "$2$1";
}
print "$out\n";
 
Or if you don't actually need to process each batch of 4 individually and are happy to process the entire string in one shot you could do this:

Code:
my $string = '74657374';       # Incoming data
$string =~ s{(..)(..)}{$2$1}g; # Byte swaps entire string
print $string, "\n";           # Output result


Trojan.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top