-
Notifications
You must be signed in to change notification settings - Fork 477
/
Copy pathfileToHex.pl
executable file
·121 lines (99 loc) · 2.34 KB
/
fileToHex.pl
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#! /usr/bin/env perl
#
# @file: fileToHex.pl
# @brief:
# @author: YoungJoo.Kim <[email protected]>
# @version:
# @date:
package FileToHex;
use strict;
use Carp;
sub new{
my($class, %cnf) = @_;
my $path = delete $cnf{path};
my $handle = delete $cnf{handle};
my $self =
bless {
path => $path,
handle => $handle
}, $class;
return bless $self;
}
sub __exit {
my $self = shift if ref ($_[0]);
my $res = shift;
Carp::carp __PACKAGE__ . ": $res->{string}";
exit($res->{return} || 1);
}
sub fileOpen {
my $self = shift if ref ($_[0]);
my $path = shift || $self->{path};
$path = $self->{path} unless defined $path;
(defined $path && -e $path) || $self->__exit({string => "error: [$path] is not defined or exists!"});
open(my $handle, "<", $path) || $self->__exit({string => "error: open(): $!"});
$self->{handle} = $handle;
return $self->{handle};
}
sub fileClose {
my $self = shift if ref ($_[0]);
my $handle = shift || $self->{handle};
$handle && close($handle);
}
sub fileReadByte {
my $self = shift if ref ($_[0]);
my $buf = \shift;
my $byte = shift || 1;
my $handle = shift || $self->{handle};
return read($handle, $$buf, $byte);
}
sub DESTROY {
my $self = shift if ref ($_[0]);
$self->fileClose();
}
1;
package main;
if ($#ARGV < 0) {
print "Usage: $0 {path} {max} {type}\n";
exit(2);
}
my $path = $ARGV[0];
my $max = $ARGV[1] || 16;
my $type = $ARGV[2] || "buffer";
my $plus = "";
my $buf = "";
my $i = 0;
my $fth = FileToHex->new(path => $path);
$fth->fileOpen();
if ($type eq "define") {
# type: define
while($fth->fileReadByte(my $c)) {
$i++;
$buf .= '\x' . unpack("H2", $c);
if (!($i % $max)) {
$plus .= "\"$buf\" \\\n";
$buf = "";
}
}
if (!($i % $max)) {
print substr($plus, 0, -3) . "\n";
} else {
print $plus . "\"$buf\"\n";
}
} else {
# type: buffer
while($fth->fileReadByte(my $c)) {
$i++;
$buf .= '0x' . unpack("H2", $c) . ', ';
if (!($i % $max)) {
$plus .= "$buf\n";
$buf = "";
}
}
if (!($i % $max)) {
print $plus . "0x00\n";
} else {
print $plus . $buf . "0x00\n";
}
}
$fth->fileClose();
# vi:set ft=perl ts=4 sw=4 et fdm=marker: