Common Lisp 언어 의 명령행 인자 처리 방법은 Common Lisp 의 구현체 마다 각각 그 방법이 다르다. 아래의 에제는 CLISP 에서 동작하는 명령행 처리 예제이다.

CLISP 에서는 ext:*args* 라는 리스트(list)형 전역변수로 받는다.
(length ext:*args*) 는 명령문에서 인자의 개수이다.

parse-number 는 대부분의 Coomon Lisp 구현체에서 동작하는 (매우 짧은) 함수로서 스트링(string)을 부동소수점수(floating point number)로 변환하는 일을 한다.

mapcar 와 apply 함수를 사용하여 (반복문 없이) 그 합을 구할 수 있게 하였다.

GNU CLisp 에서는 명령행에서 실행시 명령행 인자들은 ext:*args* 라는 리스트 타입 변수로 받을 수 있다.  예를 들어,

          프롬프트> clisp lest.lisp 1 2 3 4 5

라고 실행하면, (lengh ext:*args*) 의 값은 5 이고,  변수 ext:*args* 는 '(1 2 3 4 5) 라는 리스트를 참조하게 된다. 




 (CLisp 용) 소스파일명: testArguments.lisp
  1. #!/usr/bin/env clisp
  2. (defun parse-number (v)
  3.      (with-input-from-string (s v) (read s)))
  4. (defun main()
  5.     "명령행 인자(command-line argument) 개수 출력"
  6.     (format t "Count of arguments: ~D~%" (length ext:*args*))
  7.     (setf sum (apply #'+ 0 (mapcar #'parse-number ext:*args*)))
  8.     (format t "The sum of arguments is ~F~%" sum))
  9. (main)

 

실행> clisp testArguments.lsp 1 2 3 4
Count of arguments: 4
The sum of arguments is 10


실행> clisp testArguments.lsp 1 2 3 4.1
Count of arguments: 4
The sum of arguments is 10.1


실행> clisp  testArguments.lsp 2.5 3.1E1 -1.5e-4
Count of arguments: 3
he sum of arguments is 33.49985



Closure CL 에서는 명령행에서 실행시 명령행 인자들은 *unprocessed-command-line-arguments* 라는 리스트 타입의 전역 변수로 받을 수 있다.  예를 들어,

          프롬프트> wx86cl64 -l test.lisp -- 1 2 3 4 5

라고 실행하면, (lengh *unprocessed-command-line-arguments* ) 의 값은 5 이고,  전역변수 *unprocessed-command-line-arguments* 는 '("1" "2" "3" "4" "5") 라는 리스트를 참조하게 된다. 

wx86cl64, wx86cl, ccl, ccl64, dx86cl64, dx86cl 등의 명령으로 Common Lisp 소스파일을 싱행시킬 때는 그 소스파일명 직전에 반드시 옵션 -l 또는 --load 를 추가해야 하며, 명령행 인자들은 반드시 두 개의 마이너스 기호 -- 다음에 입력하여야 한다. 



(Clozure CL 용) 소스파일명: testArguments-2.lisp

  1.  ; #!/usr/bin/env clisp    ;  clozure cl 의 wx86cl64 명령은 이를 이식하지 못함
  2.  
  3. (defun parse-number (v)
  4.       (with-input-from-string (s v) (read s)))
  5. (defun main()
  6.       ;; 명령행 인자(command-line argument) 개수 출력
  7.     (let ((arr (list))
  8.            (sum 0))
  9.         (setf arr *unprocessed-command-line-arguments*)
  10.         (format t "Count of arguments: ~D~%" (length arr))
  11.         (setf sum (apply #'+ 0 (mapcar #'parse-number arr)))
  12.         (format t "The sum of arguments is ~F~%" sum)
  13.         (quit) ))
  14. (main)


실행> wx86cl64 -l testArguments-2.lisp -- 2 3 4 5 6
Count of arguments: 5
The sum of arguments is 20.0



Closure CL 에서는 명령행에서 실행시 명령행 인자들을 프로그램 소스에서 받을 때 전역변수  *unprocessed-command-line-arguments* 대신  전역변수  *command-line-argument-lst* 로도 받을 수 있다.  예를 들어,

          프롬프트> wx86cl64 -l test.lisp -- 1 2 3 4 5

라고 실행하면, (lengh *command-line-argument-list* ) 의 값은 9 이고,  전역변수 *unprocessed-command-line-arguments* 는 '("wx86cl64" "-l"  " test.lisp"  "--" "1" "2" "3" "4" "5") 라는 리스트를 참조하게 된다. 


(Clozure CL 용) 소스파일명: testArguments-3.lisp

  1. (defun parse-number (v)
  2.     (with-input-from-string (s v) (read s)))
  3. (defun main()
  4.     ;; 명령행 인자(command-line argument) 개수 출력
  5.      (let ((arr (list))
  6.             (sum 0))
  7.         (setf arr (last *command-line-argument-list* (- (length *command-line-argument-list*) 4)))
  8.         (format t "Count of arguments: ~D~%" (length arr))
  9.         (setf sum (apply #'+ 0 (mapcar #'parse-number arr)))
  10.         (format t "The sum of arguments is ~F~%" sum)
  11.         (quit) ))
  12. (main)


실행> wx86cl64 -l testArguments-3.lisp -- 2 3 4 5 6
Count of arguments: 5
The sum of arguments is 20.0

 

Posted by Scripter
,

Common Lisp 언어의 함수 정의 구문 양식은

       (defun functionName(parameters)
             block )

이다.

Common Lisp 언어의 반복문 양식은

       (loop for varname from start to last by step do
             block )

이다. 여기서 by step 은 생략해도 되는데 이를 생력하면 반복될 때마다 varname 이 1씩 증가한다.



소스 파일명: forTest.lisp
------------------------------[소스 시작]
(defun printDan(dan)
    (loop for i from 1 to 9 do
        (format t "~D x ~D = ~D~%" dan i (* dan i))))

(printDan 2)
------------------------------[소스 끝]

;; CLisp으로 실행하는 경우
실행> clisp -i forTest.lsp
  i i i i i i i       ooooo    o        ooooooo   ooooo   ooooo
  I I I I I I I      8     8   8           8     8     o  8    8
  I  \ `+' /  I      8         8           8     8        8    8
   \  `-+-'  /       8         8           8      ooooo   8oooo
    `-__|__-'        8         8           8           8  8
        |            8     o   8           8     o     8  8
  ------+------       ooooo    8oooooo  ooo8ooo   ooooo   8

Welcome to GNU CLISP 2.49 (2010-07-07) <http://clisp.cons.org/>

Copyright (c) Bruno Haible, Michael Stoll 1992, 1993
Copyright (c) Bruno Haible, Marcus Daniels 1994-1997
Copyright (c) Bruno Haible, Pierpaolo Bernardi, Sam Steingold 1998
Copyright (c) Bruno Haible, Sam Steingold 1999-2000
Copyright (c) Sam Steingold, Bruno Haible 2001-2010

Type :h and hit Enter for context help.

;; Loading file forTest.lsp ...
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
;; Loaded file forTest.lsp
[1]> (quit)
Bye.


;; Clozure Common Lisp으로 실행하는 경우
실행> wx86cl64 -l forTest.lsp
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
Welcome to Clozure Common Lisp Version 1.9-r15765 (WindowsX8664)!
? (quit)



Posted by Scripter
,

컨솔에 문자 출력하는 Common Lisp 구문은

       (format f "문자열(스트링)~%")

이다. 여기서 ~%는 C 언어의 개행문자 "\n"에 해당한다.

이다. 여기서 개행문자 "\n"은 추가하지 않아도 된다.

 
소스 파일명: hello.lisp
------------------------------[소스 시작]
(format t "Hello, world!~%")
(quit)
------------------------------[소스 끝]

;; 윈도우 XP에 설치된 CLISP으로 실행하는 경우:

실행> clisp
  i i i i i i i       ooooo    o        ooooooo   ooooo   ooooo
  I I I I I I I      8     8   8           8     8     o  8    8
  I  \ `+' /  I      8         8           8     8        8    8
   \  `-+-'  /       8         8           8      ooooo   8oooo
    `-__|__-'        8         8           8           8  8
        |            8     o   8           8     o     8  8
  ------+------       ooooo    8oooooo  ooo8ooo   ooooo   8

Welcome to GNU CLISP 2.49 (2010-07-07) <http://clisp.cons.org/>

Copyright (c) Bruno Haible, Michael Stoll 1992, 1993
Copyright (c) Bruno Haible, Marcus Daniels 1994-1997
Copyright (c) Bruno Haible, Pierpaolo Bernardi, Sam Steingold 1998
Copyright (c) Bruno Haible, Sam Steingold 1999-2000
Copyright (c) Sam Steingold, Bruno Haible 2001-2010

Type :h and hit Enter for context help.

[1]> (load "hello.lisp")
;; Loading file hello.lisp ...
Hello, world!
Bye.

또는

실행> clisp -i hello.lisp
  i i i i i i i       ooooo    o        ooooooo   ooooo   ooooo
  I I I I I I I      8     8   8           8     8     o  8    8
  I  \ `+' /  I      8         8           8     8        8    8
   \  `-+-'  /       8         8           8      ooooo   8oooo
    `-__|__-'        8         8           8           8  8
        |            8     o   8           8     o     8  8
  ------+------       ooooo    8oooooo  ooo8ooo   ooooo   8

Welcome to GNU CLISP 2.49 (2010-07-07) <http://clisp.cons.org/>

Copyright (c) Bruno Haible, Michael Stoll 1992, 1993
Copyright (c) Bruno Haible, Marcus Daniels 1994-1997
Copyright (c) Bruno Haible, Pierpaolo Bernardi, Sam Steingold 1998
Copyright (c) Bruno Haible, Sam Steingold 1999-2000
Copyright (c) Sam Steingold, Bruno Haible 2001-2010

Type :h and hit Enter for context help.

;; Loading file hello.lisp ...
Hello, world!
Bye.


;; 윈도우 XP의 cygwin에 설치된 CLISP으로 실행하는 경우:

실행> clisp -i hello.lisp
  i i i i i i i       ooooo    o        ooooooo   ooooo   ooooo
  I I I I I I I      8     8   8           8     8     o  8    8
  I  \ `+' /  I      8         8           8     8        8    8
   \  `-+-'  /       8         8           8      ooooo   8oooo
    `-__|__-'        8         8           8           8  8
        |            8     o   8           8     o     8  8
  ------+------       ooooo    8oooooo  ooo8ooo   ooooo   8

Welcome to GNU CLISP 2.48 (2009-07-28) <http://clisp.cons.org/>

Copyright (c) Bruno Haible, Michael Stoll 1992, 1993
Copyright (c) Bruno Haible, Marcus Daniels 1994-1997
Copyright (c) Bruno Haible, Pierpaolo Bernardi, Sam Steingold 1998
Copyright (c) Bruno Haible, Sam Steingold 1999-2000
Copyright (c) Sam Steingold, Bruno Haible 2001-2009

Type :h and hit Enter for context help.

;; Loading file hello.lisp ...
Hello, world!
Bye.


 

;; 윈도우 7에 설치된 Clozure Common LISP으로 실행하는 경우:

실행> wx86cl -l hello.lisp
Hello, world!

또는

실행> wx86cl64 -l hello.lisp
Hello, world!


Posted by Scripter
,

 

ErLang 언어 소스:

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Filename: testHexView_03.erl
%
% Compile: erlc testHexView_03.erl
% Execute: erl -f [filename] -run testHexView_03 main -run init stop -noshell
%
%    Date: 2013. 8. 24.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

-module(testHexView_03).
-export([main/0]).

toHex(N) ->
    X1 = (N band 16#F0) bsr 4,
    X2 = N band 16#F,
    S1 = if X1 < 10  -> string:chars($0 + X1, 1);
            X1 >= 10 -> string:chars($A + X1 - 10, 1)
         end,
    S2 = if X2 <  10 -> string:chars($0 + X2, 1);
            X2 >= 10 -> string:chars($A + X2 - 10, 1)
         end,
    S1 ++ S2.

toHex8(N) ->
    X1 = (N band 16#F0000000) bsr 28,
    X2 = (N band 16#F000000) bsr 24,
    X3 = (N band 16#F00000) bsr 20,
    X4 = (N band 16#F0000) bsr 16,
    X5 = (N band 16#F000) bsr 12,
    X6 = (N band 16#F00) bsr 8,
    X7 = (N band 16#F0) bsr 4,
    X8 = N band 16#F,
    S1 = if X1 < 10  -> string:chars($0 + X1, 1);
            X1 >= 10 -> string:chars($A + X1 - 10, 1)
         end,
    S2 = if X2 <  10 -> string:chars($0 + X2, 1);
            X2 >= 10 -> string:chars($A + X2 - 10, 1)
         end,
    S3 = if X3 <  10 -> string:chars($0 + X3, 1);
            X3 >= 10 -> string:chars($A + X3 - 10, 1)
         end,
    S4 = if X4 <  10 -> string:chars($0 + X4, 1);
            X4 >= 10 -> string:chars($A + X4 - 10, 1)
         end,
    S5 = if X5 <  10 -> string:chars($0 + X5, 1);
            X5 >= 10 -> string:chars($A + X5 - 10, 1)
         end,
    S6 = if X6 <  10 -> string:chars($0 + X6, 1);
            X6 >= 10 -> string:chars($A + X6 - 10, 1)
         end,
    S7 = if X7 <  10 -> string:chars($0 + X7, 1);
           X7 >= 10 -> string:chars($A + X7 - 10, 1)
          end,
    S8 = if X8 <  10 -> string:chars($0 + X8, 1);
            X8 >= 10 -> string:chars($A + X8 - 10, 1)
         end,
    S1 ++ S2 ++ S3 ++ S4 ++ " " ++ S5 ++ S6 ++ S7 ++ S8.


raw_read_file(Path) ->
    {ok, File} = file:open(Path, [read, binary]),
    raw_read_loop(File, []).

raw_read_loop(File, Acc) ->
    case file:read(File, 1024) of
        {ok, Bytes} ->
            raw_read_loop(File, [Acc | Bytes]);
        eof ->
            file:close(File),
            iolist_to_binary(Acc);
        {error, Reason} ->
            file:close(File),
            erlang:error(Reason)
    end.


 

getHexStr(S, Offset, K, Cnt, T) ->
    if
        K =:= Cnt -> T;
        K =/= Cnt -> C0 = if
                              K =:= 8 -> "-";
                              K =/= 8 -> " "
                           end,
                     getHexStr(S, Offset, K + 1, Cnt, T ++ C0 ++ (toHex (binary:at(S, Offset + K))))
    end.


getDumStr(S, Offset, K, Cnt, T) ->
    if
        K =:= Cnt -> T;
        K =/= Cnt -> X = binary:at(S, Offset + K),
                     A = if
                            (X < 16#20) or (X > 16#7F) -> $.;
                            true                       -> X
                         end,
                     getDumStr(S, Offset, K + 1, Cnt, T ++ string:chars(A, 1))
    end.


printHexTable(S, Offset, Size) ->
    case (Offset + 16) =< Size of
      true  -> io:fwrite("~s: ", [toHex8(Offset)]),
               io:fwrite("~s", [getHexStr(S, Offset, 0, 16, "")]),
               io:fwrite("  |~s|~n", [getDumStr(S, Offset, 0 ,16, "")]),
               printHexTable(S, Offset + 16, Size);
      _Else -> io:fwrite("~s: ", [toHex8(Offset)]),
               io:fwrite("~s", [getHexStr(S, Offset, 0, Size - Offset, "")]),
               io:fwrite("~s", [string:chars(16#20,  3*(16 - Size + Offset))]),
               io:fwrite("  |~s", [getDumStr(S, Offset, 0, Size - Offset, "")]),
               io:fwrite("~s|~n", [string:chars(16#20, 16 - Size + Offset)])
    end.

 

file_exist(Filename) ->
    case file:read_file_info(Filename) of
        {ok, _}         -> true;
        {error, enoent} -> false;
        {error, Reason} -> io:format("~s is ~s~n", [Filename, Reason]),
                           false
    end.


 

main() ->
    {ok, TMP} = init:get_argument(f),
    Fname1 = lists:nth(1, TMP),
    Fname = lists:nth(1, Fname1),
    case filelib:is_dir(Fname) of
           true  -> io:format("\"~s\" is a directory.~n", [Fname]),
                    halt();
           _Else  -> io:format("")
    end,
    case file_exist(Fname) of
           false  -> io:format("The file \"~s\" does not exist.~n", [Fname]),
                     halt();
           true  -> io:format("")
    end,

    B = raw_read_file(Fname),

    io:fwrite("The size of the file \"~s\" is ~w.~n~n", [Fname, size(B)]),

    printHexTable(B, 0, size(B)),

    io:fwrite("~nRead ~w bytes.~n", [size(B)]),

    0.

 

 

싱행 예 1> erl -f temp_1.bin -run testHexView_03 main -run init stop -noshell
The size of the file "temp_1.bin" is 12.

0000 0000:  48 65 6C 6C 6F 20 74 68-65 72 65 0A              |Hello there.    |

Read 12 bytes.

싱행 예 1> erl -f myFile.ser -run testHexView_03 main -run init stop -noshell
The size of the file "myFile.ser" is 130.

0000 0000:  AC ED 00 05 73 72 00 06-50 65 72 73 6F 6E 07 31  |....sr..Person.1|
0000 0010:  46 DB A5 1D 44 AB 02 00-03 49 00 03 61 67 65 4C  |F...D....I..ageL|
0000 0020:  00 09 66 69 72 73 74 4E-61 6D 65 74 00 12 4C 6A  |..firstNamet..Lj|
0000 0030:  61 76 61 2F 6C 61 6E 67-2F 53 74 72 69 6E 67 3B  |ava/lang/String;|
0000 0040:  4C 00 08 6C 61 73 74 4E-61 6D 65 71 00 7E 00 01  |L..lastNameq.~..|
0000 0050:  78 70 00 00 00 13 74 00-05 4A 61 6D 65 73 74 00  |xp....t..Jamest.|
0000 0060:  04 52 79 61 6E 73 71 00-7E 00 00 00 00 00 1E 74  |.Ryansq.~......t|
0000 0070:  00 07 4F 62 69 2D 77 61-6E 74 00 06 4B 65 6E 6F  |..Obi-want..Keno|
0000 0080:  62 69                                            |bi              |

Read 130 bytes.

 

 

Posted by Scripter
,

 

OCaml 언어 소스:

(*
   Filename: testHexView_02.ml
 
   Execute: ocaml testHexView_02.ml [filename]

     Or
 
   Compile: ocamlc -o testHexView_02 testHexView_02.ml
   Execute: ./testHexView_02 [filename]
 
     Or
 
   Compile: ocamlc -o testHexView_02.exe testHexView_02.ml
   Execute: testHexView_02 [filename]
 
   Date: 2013. 8. 20.
*)

open Printf;;

let printUsage() =
    printf("Usgae: testHexView_02 [filename]\n");;

let toHex n =
    let s = ref "" in
    let x1 = (n land 0xF0) lsr 4 in
    let x2 = n land 0xF in
    if x1 < 10 then
        s := !s ^ Char.escaped (Char.chr( Char.code('0') + x1 ))
    else
        s := !s ^ Char.escaped (Char.chr( Char.code('A') + (x1 - 10) ));
    if x2 < 10 then
        s := !s ^ Char.escaped (Char.chr( Char.code('0') + x2 ))
    else
        s := !s ^ Char.escaped (Char.chr( Char.code('A') + (x2 - 10) ));
    !s


let toHex8 n =
    let s = ref "" in
    (* let x1 = (n land 0xF0000000) lsr 28 in *)
    let x1 = (n land 0x70000000) lsr 28 in
    let x2 = (n land 0xF000000) lsr 24 in
    let x3 = (n land 0xF00000) lsr 20 in
    let x4 = (n land 0xF0000) lsr 18 in
    let x5 = (n land 0xF000) lsr 12 in
    let x6 = (n land 0xF00) lsr 8 in
    let x7 = (n land 0xF0) lsr 4 in
    let x8 = n land 0xF in
    if x1 < 10 then
        s := !s ^ Char.escaped (Char.chr( Char.code('0') + x1 ))
    else
        s := !s ^ Char.escaped (Char.chr( Char.code('A') + (x1 - 10) ));
    if x2 < 10 then
        s := !s ^ Char.escaped (Char.chr( Char.code('0') + x2 ))
    else
        s := !s ^ Char.escaped (Char.chr( Char.code('A') + (x2 - 10) ));
    if x3 < 10 then
        s := !s ^ Char.escaped (Char.chr( Char.code('0') + x3 ))
    else
        s := !s ^ Char.escaped (Char.chr( Char.code('A') + (x3 - 10) ));
    if x4 < 10 then
        s := !s ^ Char.escaped (Char.chr( Char.code('0') + x4 ))
    else
        s := !s ^ Char.escaped (Char.chr( Char.code('A') + (x4 - 10) ));
    s := !s ^ " ";
    if x5 < 10 then
        s := !s ^ Char.escaped (Char.chr( Char.code('0') + x5 ))
    else
        s := !s ^ Char.escaped (Char.chr( Char.code('A') + (x5 - 10) ));
    if x6 < 10 then
        s := !s ^ Char.escaped (Char.chr( Char.code('0') + x6 ))
    else
        s := !s ^ Char.escaped (Char.chr( Char.code('A') + (x6 - 10) ));
    if x7 < 10 then
        s := !s ^ Char.escaped (Char.chr( Char.code('0') + x7 ))
    else
        s := !s ^ Char.escaped (Char.chr( Char.code('A') + (x7 - 10) ));
    if x8 < 10 then
        s := !s ^ Char.escaped (Char.chr( Char.code('0') + x8 ))
    else
        s := !s ^ Char.escaped (Char.chr( Char.code('A') + (x8 - 10) ));
    !s

let load_file f =
  let ic = open_in f in
  let n = in_channel_length ic in
  let s = String.create n in
  really_input ic s 0 n;
  close_in ic;
  (s);;

 

if Array.length Sys.argv < 2 then begin
    printUsage() ;
    exit 1
end;

let fname = Sys.argv.(1) in

if not (Sys.file_exists fname) then begin
    printf "The file \"%s\" does not exist.\n" fname;
    exit 1
end;

if (Sys.is_directory fname) then begin
    printf "\"%s\" is a directory.\n" fname;
    exit 1
end;

let dum = ref "" in
let bstr = load_file Sys.argv.(1) in 
let fsize = String.length bstr in 

printf "The size of the file \"%s\" is %d.\n" fname fsize;
print_newline();


let n = ref 0 in
while (!n < fsize) do
    if (!n mod 16) == 0 then begin
        printf  "%s: " (toHex8 !n)
    end;
    let c = bstr.[!n] in
    (* print_char c   *)
    if (!n mod 16) == 8 then
        printf  "-%s" (toHex (Char.code c))
    else
        printf  " %s" (toHex (Char.code c));
    if (Char.code c) < (Char.code ' ') or (Char.code c) > 0x7F then
        dum := !dum ^ "."
    else
        dum := !dum ^ (Char.escaped c);
    if (!n mod 16) == 15 then begin
        printf  "  |%s|\n" !dum;
        dum := ""
    end;
    n := !n + 1;
done;

if (!n mod 16) > 0 then begin
    for i = 0 to (pred (16 - (!n mod 16))) do
        printf  "   "
    done;
    printf  "  |%s" !dum;
    for i = 0 to (pred (16 - (!n mod 16))) do
        printf  " "
    done;
    printf  "|\n";
    dum := ""
end;

print_newline();
printf "Read %d bytes.\n" !n;

 

 

실행 예 1> testHexView_02 temp_1.bin
The size of the file "temp_1.bin" is 12.

0000 0000:  48 65 6C 6C 6F 20 74 68-65 72 65 0A              |Hello there.    |

Read 12 bytes.

실행 예 2> testHexView_02 myFile.ser
The size of the file "myFile.ser" is 130.

0000 0000:  AC ED 00 05 73 72 00 06-50 65 72 73 6F 6E 07 31  |....sr..Person.1|
0000 0010:  46 DB A5 1D 44 AB 02 00-03 49 00 03 61 67 65 4C  |F...D....I..ageL|
0000 0020:  00 09 66 69 72 73 74 4E-61 6D 65 74 00 12 4C 6A  |..firstNamet..Lj|
0000 0030:  61 76 61 2F 6C 61 6E 67-2F 53 74 72 69 6E 67 3B  |ava/lang/String;|
0000 0040:  4C 00 08 6C 61 73 74 4E-61 6D 65 71 00 7E 00 01  |L..lastNameq.~..|
0000 0050:  78 70 00 00 00 13 74 00-05 4A 61 6D 65 73 74 00  |xp....t..Jamest.|
0000 0060:  04 52 79 61 6E 73 71 00-7E 00 00 00 00 00 1E 74  |.Ryansq.~......t|
0000 0070:  00 07 4F 62 69 2D 77 61-6E 74 00 06 4B 65 6E 6F  |..Obi-want..Keno|
0000 0080:  62 69                                            |bi              |

Read 130 bytes.

 

 

Posted by Scripter
,

 

Haskell 언어 소스:

{-
    Filename: testHexView_02.hs

      Purpose: Show hexadecimal values of the given file.
 
    Compile: ghc testHexView_02.hs
    Execute: testHexView_02 [filename]
 
    Date: 2013. 8. 20.
-}

module Main where

import System.Directory
import System.Exit
import System.IO
import System.Environment
import Text.Printf
import Data.Bits
import Data.Char (ord)
import Data.Char (chr)
import Data.Array
import Data.List


printUsage :: IO()
printUsage = putStrLn "Usage: testHexView_02 [filename]"


strDupLoop :: String -> Integer -> String -> String
strDupLoop s n t = case n == 0 of
        True -> t
        _ -> strDupLoop s (n - 1) (t ++ s)

strDup :: String -> Integer -> String
strDup s n = strDupLoop s n ""

getHexStr :: String -> Integer -> Integer -> Integer -> String -> String
getHexStr s offset k cnt t = case k == cnt of
        True -> t
        _ -> getHexStr s offset (k + 1) cnt (t ++ c0 ++ (printf "%s" (toHex (ord (s !! (fromInteger (offset + k)))))))
                       where c0 = if k == 8 then "-" else " "

getDumStr :: String -> Integer -> Integer -> Integer -> String -> String
getDumStr s offset k cnt t = case k == cnt of
        True -> t
        _ -> getDumStr s offset (k + 1) cnt (t ++ (printf "%c" a))
                 where x = (s !! (fromInteger (offset + k)))
                       a = if (ord x) < (ord ' ') || (ord x) > 0x7F
                              then '.'
                              else x

printHexTable :: String -> Integer -> Integer -> IO()
printHexTable s offset size = case offset + 16 <= size of
    True -> do putStr $ printf "%s: " (toHex8 $ fromInteger offset)
               putStr (getHexStr s offset 0 16 "")
               putStrLn $ "  |" ++ (getDumStr s offset 0 16 "") ++ "|"
               printHexTable s (offset + 16) size
    _    -> do putStr $ printf "%s: " (toHex8 $ fromInteger offset)
               putStr (getHexStr s offset 0 (size - offset) "")
               putStr (strDup "   " (16 - size + offset))
               putStr $ "  |" ++ (getDumStr s offset 0 (size - offset) "")
               putStrLn $ (strDup " " (16 - size + offset)) ++ "|"
   

toHex :: Int -> [Char]
toHex n = printf "%c%c" sx1 sx2
          where x1 = shiftR (n .&. 0xF0) 4
                x2 = n .&. 0xF
                -- sx1 = show ((ord '0') + x1)
                -- sx2 = show ((ord 'A') + x2)
                sx1  = if x1 > 9
                       then
                            ((ord 'A') + (x1 - 10))
                       else
                            ((ord '0') + x1)
                sx2 = if x2 > 9
                      then
                            ((ord 'A') + (x2 - 10))
                      else
                            ((ord '0') + x2)


toHex8 :: Int -> [Char]
toHex8 n = printf "%c%c%c%c %c%c%c%c" sx1 sx2 sx3 sx4 sx5 sx6 sx7 sx8
          where x1 = shiftR (n .&. 0xF0000000) 28
                x2 = shiftR (n .&. 0xF000000) 24
                x3 = shiftR (n .&. 0xF00000) 20
                x4 = shiftR (n .&. 0xF0000) 16
                x5 = shiftR (n .&. 0xF000) 12
                x6 = shiftR (n .&. 0xF00) 8
                x7 = shiftR (n .&. 0xF0) 4
                x8 = n .&. 0xF
                sx1  = if x1 > 9
                       then
                            ((ord 'A') + (x1 - 10))
                       else
                            ((ord '0') + x1)
                sx2 = if x2 > 9
                      then
                            ((ord 'A') + (x2 - 10))
                      else
                            ((ord '0') + x2)
                sx3 = if x3 > 9
                      then
                            ((ord 'A') + (x3 - 10))
                      else
                            ((ord '0') + x3)
                sx4 = if x4 > 9
                      then
                            ((ord 'A') + (x4 - 10))
                      else
                            ((ord '0') + x4)
                sx5 = if x5 > 9
                      then
                            ((ord 'A') + (x5 - 10))
                      else
                            ((ord '0') + x5)
                sx6 = if x6 > 9
                      then
                            ((ord 'A') + (x6 - 10))
                      else
                            ((ord '0') + x6)
                sx7 = if x7 > 9
                      then
                            ((ord 'A') + (x7 - 10))
                      else
                            ((ord '0') + x7)
                sx8 = if x8 > 9
                      then
                            ((ord 'A') + (x8 - 10))
                      else
                            ((ord '0') + x8)


       
main :: IO ()
main = do
    args <- getArgs

    if (length args == 0)
       then do printUsage
               exitWith (ExitFailure 1)
       else do

    let fname = args !! 0

    dirExist <- doesDirectoryExist fname
    if dirExist
       then do putStrLn $ printf "%s is a directory." fname
               exitWith (ExitFailure 1)
       else do

    fileExist <- doesFileExist fname
    if not fileExist
       then do putStrLn $ printf "The file \"%s\" does not exist." fname
               exitWith (ExitFailure 1)
       else do
    inh <- openFile fname ReadMode
    fsize <- hFileSize inh
    inpStr <- hGetContents inh

    putStrLn $ printf "The size of the file \"%s\" is %d." fname fsize
    putStrLn ""

    printHexTable inpStr 0 fsize

    putStrLn ""
    putStrLn $ printf "Read %d bytes." fsize

    hClose inh

 

 

실행 예 1> testHexView_02 temp_1.bin
The size of the file "temp_1.bin" is 12.

0000 0000:  48 65 6C 6C 6F 20 74 68-65 72 65 0A              |Hello there.    |

Read 12 bytes.

실행 예 2> testHexView_02 myFile.ser
The size of the file "myFile.ser" is 130.

0000 0000:  AC ED 00 05 73 72 00 06-50 65 72 73 6F 6E 07 31  |....sr..Person.1|
0000 0010:  46 DB A5 1D 44 AB 02 00-03 49 00 03 61 67 65 4C  |F...D....I..ageL|
0000 0020:  00 09 66 69 72 73 74 4E-61 6D 65 74 00 12 4C 6A  |..firstNamet..Lj|
0000 0030:  61 76 61 2F 6C 61 6E 67-2F 53 74 72 69 6E 67 3B  |ava/lang/String;|
0000 0040:  4C 00 08 6C 61 73 74 4E-61 6D 65 71 00 7E 00 01  |L..lastNameq.~..|
0000 0050:  78 70 00 00 00 13 74 00-05 4A 61 6D 65 73 74 00  |xp....t..Jamest.|
0000 0060:  04 52 79 61 6E 73 71 00-7E 00 00 00 00 00 1E 74  |.Ryansq.~......t|
0000 0070:  00 07 4F 62 69 2D 77 61-6E 74 00 06 4B 65 6E 6F  |..Obi-want..Keno|
0000 0080:  62 69                                            |bi              |

Read 130 bytes.

 

 

Posted by Scripter
,

 

F# 언어 소스:

(* Filename: testHexView_02.fs
 *
 * Compile: fsc testHexView_02.fs
 * Execute: testHexView_02 [filename]
 *
 * Date: 2013. 8. 18.
 *)

open System
open System.IO

let Value (c:char) =
    (int c) - (int 'A') + 1


let toHex n =
    let mutable s = ""
    let x1 = (n &&& 0xF0) >>> 4
    let x2 = n &&& 0xF
    if x1 < 10 then
        s <- s + (sprintf "%c" (char (x1 + (int '0'))))
    else
        s <- s + (sprintf "%c" (char (x1 - 10 + (int 'A'))))
    if x2 < 10 then
        s <- s + (sprintf "%c" (char (x2 + (int '0'))))
    else
        s <- s + (sprintf "%c" (char (x2 - 10 + (int 'A'))))
    s
   
let toHex8 n =
    let mutable s = ""
    let x1 = (n &&& 0xF0000000) >>> 28
    let x2 = (n &&& 0xF000000) >>> 24
    let x3 = (n &&& 0xF00000) >>> 20
    let x4 = (n &&& 0xF0000) >>> 16
    let x5 = (n &&& 0xF000) >>> 12
    let x6 = (n &&& 0xF00) >>> 18
    let x7 = (n &&& 0xF0) >>> 4
    let x8 = n &&& 0xF
    if x1 < 10 then
        s <- s + (sprintf "%c" (char (x1 + (int '0'))))
    else
        s <- s + (sprintf "%c" (char (x1 - 10 + (int 'A'))))
    if x2 < 10 then
        s <- s + (sprintf "%c" (char (x2 + (int '0'))))
    else
        s <- s + (sprintf "%c" (char (x2 - 10 + (int 'A'))))
    if x3 < 10 then
        s <- s + (sprintf "%c" (char (x3 + (int '0'))))
    else
        s <- s + (sprintf "%c" (char (x3 - 10 + (int 'A'))))
    if x4 < 10 then
        s <- s + (sprintf "%c" (char (x4 + (int '0'))))
    else
        s <- s + (sprintf "%c" (char (x4 - 10 + (int 'A'))))
    s <- s + " "
    if x5 < 10 then
        s <- s + (sprintf "%c" (char (x5 + (int '0'))))
    else
        s <- s + (sprintf "%c" (char (x5 - 10 + (int 'A'))))
    if x6 < 10 then
        s <- s + (sprintf "%c" (char (x6 + (int '0'))))
    else
        s <- s + (sprintf "%c" (char (x6 - 10 + (int 'A'))))
    if x7 < 10 then
        s <- s + (sprintf "%c" (char (x7 + (int '0'))))
    else
        s <- s + (sprintf "%c" (char (x7 - 10 + (int 'A'))))
    if x8 < 10 then
        s <- s + (sprintf "%c" (char (x8 + (int '0'))))
    else
        s <- s + (sprintf "%c" (char (x8 - 10 + (int 'A'))))
    s
    
   
[<EntryPoint>]
let main args =

    if args.Length < 1 then
        eprintfn "Usage: testHexView_02 [filename]"
        exit 1
    let fname = args.[0]

    if Directory.Exists(fname) then
          printfn "\"%s\" is a directory." fname
          exit 1

    let file = new FileInfo(fname)
    if not file.Exists then
          printfn "The file \"%s\" does not exist." fname
          exit 1
    let fsize = file.Length

    printfn "The size of the file \"%s\" is %d." fname fsize
    printfn ""

    let fs = IO.File.OpenRead fname
    let currentByte = ref 0
    let mutable n = 0
    let mutable dum = ""
    while (int64 n) < fsize do
        if (n % 16) = 0 then
            printf "%s: " (toHex8 n)
        currentByte := fs.ReadByte()
        if (int !currentByte) < (int ' ') || (int !currentByte) > 0x7F then
            dum <- dum + "."
        else
            dum <- dum + (sprintf "%c" (char !currentByte))
        if (n % 16) = 8 then
            printf "-%s" (toHex (int !currentByte))
        else
            printf " %s" (toHex (int !currentByte))
        if (n % 16) = 15 then
            printfn "  |%s|" dum
            dum <- ""
        n <- n + 1
    if (n % 16) > 0 then
        for i = 1 to (16 - (n % 16)) do
            printf "   "
        printf "  |%s" dum
        for i = 1 to (16 - (n % 16)) do
            printf " "
        printfn "|"
        dum <- ""

    fs.Close()
    printfn "\nRead %d bytes." n

    0

 

실행 예 1> testHexView_02 temp_1.bin
The size of the file "temp_1.bin" is 12.

0000 0000:  48 65 6C 6C 6F 20 74 68-65 72 65 0A              |Hello there.    |

Read 12 bytes.

실행 예 2> testHexView_02 myFile.ser
The size of the file "myFile.ser" is 130.

0000 0000:  AC ED 00 05 73 72 00 06-50 65 72 73 6F 6E 07 31  |....sr..Person.1|
0000 0010:  46 DB A5 1D 44 AB 02 00-03 49 00 03 61 67 65 4C  |F...D....I..ageL|
0000 0020:  00 09 66 69 72 73 74 4E-61 6D 65 74 00 12 4C 6A  |..firstNamet..Lj|
0000 0030:  61 76 61 2F 6C 61 6E 67-2F 53 74 72 69 6E 67 3B  |ava/lang/String;|
0000 0040:  4C 00 08 6C 61 73 74 4E-61 6D 65 71 00 7E 00 01  |L..lastNameq.~..|
0000 0050:  78 70 00 00 00 13 74 00-05 4A 61 6D 65 73 74 00  |xp....t..Jamest.|
0000 0060:  04 52 79 61 6E 73 71 00-7E 00 00 00 00 00 1E 74  |.Ryansq.~......t|
0000 0070:  00 07 4F 62 69 2D 77 61-6E 74 00 06 4B 65 6E 6F  |..Obi-want..Keno|
0000 0080:  62 69                                            |bi              |

Read 130 bytes.

 

 

 

 

Posted by Scripter
,

 

Octave 언어 소스:

% Filename: testHexView_02.m
%
% Execute: octave -qf testHexView_02.m [filename]
%
% Date: 2013. 8. 18.

function printUsage()
    printf("Usage: octave -qf testHexView_02.m [filename]\n");
endfunction

function y = getFileSize(fd)
    n = ftell(fd);
    fseek(fd, 0, SEEK_END);
    x = ftell(fd);
    fseek(fd, n, SEEK_SET);
    y = x;
endfunction

function y = toHex(n)
    s = "";
    x1 = bitshift(bitand(n, 0xF0), -4);
    x2 = bitand(n, 0xF);
    if (x1 < 10)
        s = strcat(s, char(toascii('0') + x1));
    else
        s = strcat(s, char(toascii('A') + (x1 - 10)));
    endif
    % printf("s = %s\n", s);
    if (x2 < 10)
        s = strcat(s, char(toascii('0') + x2));
    else
        s = strcat(s, char(toascii('A') + (x2 - 10)));
    endif
    % printf("s = %s\n", s);
    y = s;
endfunction

function y = toHex8(n)
    s = "";
    % printf("s = %s\n", s);
    x1 = bitshift(bitand(n, 0xF0000000), -28);
    x2 = bitshift(bitand(n, 0xF000000), -24);
    x3 = bitshift(bitand(n, 0xF00000), -20);
    x4 = bitshift(bitand(n, 0xF0000), -16);
    x5 = bitshift(bitand(n, 0xF000), -12);
    x6 = bitshift(bitand(n, 0xF00), -8);
    x7 = bitshift(bitand(n, 0xF0), -4);
    x8 = bitand(n, 0xF);
    if (x1 < 10)
        s = strcat(s, char(toascii('0') + x1));
    else
        s = strcat(s, char(toascii('A') + (x1 - 10)));
    endif
    if (x2 < 10)
        s = strcat(s, char(toascii('0') + x2));
    else
        s = strcat(s, char(toascii('A') + (x2 - 10)));
    endif
    if (x3 < 10)
        s = strcat(s, char(toascii('0') + x3));
    else
        s = strcat(s, char(toascii('A') + (x3 - 10)));
    endif
    if (x4 < 10)
        s = strcat(s, char(toascii('0') + x4));
    else
        s = strcat(s, char(toascii('A') + (x4 - 10)));
    endif
    %% s = sprintf("%s -", s);
    if (x5 < 10)
        % s = strcat(s, char(toascii('0') + x5));
        s = sprintf("%s %c", s, char(toascii('0') + x5));
    else
        % s = strcat(s, char(toascii('A') + (x5 - 10)));
        s = sprintf("%s %c", s, char(toascii('A') + (x5 - 10)));
    endif
    if (x6 < 10)
        s = strcat(s, char(toascii('0') + x6));
    else
        s = strcat(s, char(toascii('A') + (x6 - 10)));
    endif
    if (x7 < 10)
        s = strcat(s, char(toascii('0') + x7));
    else
        s = strcat(s, char(toascii('A') + (x7 - 10)));
    endif
    if (x8 < 10)
        s = strcat(s, char(toascii('0') + x8));
    else
        s = strcat(s, char(toascii('A') + (x8 - 10)));
    endif
    y = s;
endfunction

 

arg_list = argv ();
if nargin < 1
    printUsage();
    quit;
endif

fname = arg_list{1};

if exist(fname, "dir")
    printf("\"%s\" is a directory.\n", fname);
    quit;
endif

if ! exist(fname, "file")
    printf("The file \"%s\" does not exist.\n", fname);
    quit;
endif

f = fopen(fname, "rb");

fsize = getFileSize(f);

printf("The size of the file \"%s\" is %d.\n", fname, fsize);
printf("\n");

fseek(f, 0, SEEK_SET);
n = 0;
dum = "";
while n < fsize
    if mod(n, 16) == 0
        printf("%s: ", toHex8(n));
    endif
    [val, count] = fread (f, 1);
    if mod(n, 16) == 8
        printf("-%s", toHex(val));
    else
        printf(" %s", toHex(val));
    endif
    if toascii(val) < toascii(' ') || toascii(val) > 0x7F
        dum = sprintf("%s%c", dum, '.');
    else
        dum = sprintf("%s%c", dum, toascii(val));
    endif
    if mod(n, 16) == 15
        printf("  |%s|\n", dum);
        dum = "";
    endif
    n = n + 1;
endwhile

if mod(n, 16) > 0
    for i = 1 : 16 - mod(n, 16)
        printf("   ");
    endfor
    printf("  |%s", dum);
    for i = 1 : 16 - mod(n, 16)
        printf(" ");
    endfor
    printf("|\n");
    dum = "";
endif

fclose(f);

printf("\nRead %d bytes.\n", n);


 

실행 예 1> octave -qf testHexView_02.m .\temp_1.bin
The size of the file ".\temp_1.bin" is 12.

0000 0000:  48 65 6C 6C 6F 20 74 68-65 72 65 0A              |Hello there.    |

Read 12 bytes.


실행 예 2> octave -qf testHexView_02.m .\myFile.ser
The size of the file ".\myFile.ser" is 130.

0000 0000:  AC ED 00 05 73 72 00 06-50 65 72 73 6F 6E 07 31  |,m..sr..Person.1|
0000 0010:  46 DB A5 1D 44 AB 02 00-03 49 00 03 61 67 65 4C  |F[%.D+...I..ageL|
0000 0020:  00 09 66 69 72 73 74 4E-61 6D 65 74 00 12 4C 6A  |..firstNamet..Lj|
0000 0030:  61 76 61 2F 6C 61 6E 67-2F 53 74 72 69 6E 67 3B  |ava/lang/String;|
0000 0040:  4C 00 08 6C 61 73 74 4E-61 6D 65 71 00 7E 00 01  |L..lastNameq.~..|
0000 0050:  78 70 00 00 00 13 74 00-05 4A 61 6D 65 73 74 00  |xp....t..Jamest.|
0000 0060:  04 52 79 61 6E 73 71 00-7E 00 00 00 00 00 1E 74  |.Ryansq.~......t|
0000 0070:  00 07 4F 62 69 2D 77 61-6E 74 00 06 4B 65 6E 6F  |..Obi-want..Keno|
0000 0080:  62 69                                            |bi              |

Read 130 bytes.

 

 

 

 

Posted by Scripter
,

 

R 언어 소스:

# Filename: testHexView_02.r
#
#     Purpose: Show hexademial values of the given binary file.
#
#     Require: R 3.0.1 above
#
# Execute: r --silent --slave -q -f testHexView_02.r --args [filename]
#
# Date: 2013. 8. 17.


asc <- function(x) { strtoi(charToRaw(x),16L) }
chr <- function(n) { rawToChar(as.raw(n)) }


 

toHex = function(n) {
    s <- ""
    x1 <- bitwShiftR(as.integer(as.hexmode(n) & as.hexmode(0xF0)), 4)
    x2 <- as.integer(as.hexmode(n) & as.hexmode(0xF))
    if (x1 < 10) {
        s = sprintf("%s%s", s, chr(asc("0") + x1))
    } else {
        s = sprintf("%s%s", s, chr(asc("A") + (x1 - 10)))
    }
    if (x2 < 10) {
        s = sprintf("%s%s", s, chr(asc("0") + x2))
    } else {
        s = sprintf("%s%s", s, chr(asc("A") + (x2 - 10)))
    }
    s
}

toHex8 = function(n) {
    s <- ""
    s = sprintf("%s%s", s, "0")
    x2 <- bitwShiftR(as.integer(as.hexmode(n) & as.hexmode(0xF000000L)), 24)
    x3 <- bitwShiftR(as.integer(as.hexmode(n) & as.hexmode(0xF00000L)), 20)
    x4 <- bitwShiftR(as.integer(as.hexmode(n) & as.hexmode(0xF0000L)), 16)
    x5 <- bitwShiftR(as.integer(as.hexmode(n) & as.hexmode(0xF000L)), 12)
    x6 <- bitwShiftR(as.integer(as.hexmode(n) & as.hexmode(0xF00L)), 8)
    x7 <- bitwShiftR(as.integer(as.hexmode(n) & as.hexmode(0xF0L)), 4)
    x8 <- as.integer(as.hexmode(n) & as.hexmode(0xFL))
    if (x2 < 10) {
        s = sprintf("%s%s", s, chr(asc("0") + x2))
    } else {
        s = sprintf("%s%s", s, chr(asc("A") + (x2 - 10)))
    }
    if (x3 < 10) {
        s = sprintf("%s%s", s, chr(asc("0") + x3))
    } else {
        s = sprintf("%s%s", s, chr(asc("A") + (x3 - 10)))
    }
    if (x4 < 10) {
        s = sprintf("%s%s", s, chr(asc("0") + x4))
    } else {
        s = sprintf("%s%s", s, chr(asc("A") + (x4 - 10)))
    }
    s = sprintf("%s%s", s, " ")
    if (x5 < 10) {
        s = sprintf("%s%s", s, chr(asc("0") + x5))
    } else {
        s = sprintf("%s%s", s, chr(asc("A") + (x5 - 10)))
    }
    if (x6 < 10) {
        s = sprintf("%s%s", s, chr(asc("0") + x6))
    } else {
        s = sprintf("%s%s", s, chr(asc("A") + (x6 - 10)))
    }
    if (x7 < 10) {
        s = sprintf("%s%s", s, chr(asc("0") + x7))
    } else {
        s = sprintf("%s%s", s, chr(asc("A") + (x7 - 10)))
    }
    if (x8 < 10) {
        s = sprintf("%s%s", s, chr(asc("0") + x8))
    } else {
        s = sprintf("%s%s", s, chr(asc("A") + (x8 - 10)))
    }
    s
}


args <- commandArgs(trailingOnly = TRUE)

fname <- "c:\\test\\java7\\temp_1.bin"

if (length(args) > 0) {
    fname = args[1]
} else {
    cat("Usage: r --silent --slave -q -f testHexView_02.r --args [filename]\n")
    q()
}

if (file.exists(fname) == FALSE) {
    cat(sprintf("The file \"%s\" does not exist.\n", fname))
    q()
}

finfo <- file.info(fname)

if (finfo$isdir) {
    cat(sprintf("\"%s\" is a directory.\n", fname))
    q()
}

fsize <- finfo$size
cat(sprintf("The size of the file \"%s\" is %d.\n", fname, fsize))
cat("\n")

zz <- file(fname, "rb")
n = 0
dum = ""
while (n < fsize) {
    if ((n %% 16) == 0) {
        cat(toHex8(n))
        cat(": ")
    }
    c <- readBin(con=zz, what="raw", n=1)
    if ((n %% 16) == 8) {
        cat("-")
    } else {
        cat(" ")
    }
    cat(toHex(as.integer(c)))
    if (as.integer(c) < 0x20 | as.integer(c) > 0x7F) {
        dum = sprintf("%s.", dum)
    } else {
        dum = sprintf("%s%s", dum, chr(as.integer(c)))
    }

    if ((n %% 16) == 15) {
        cat("  |")
        cat(dum)
        cat("|\n")
        dum = ""
    }
    n = n + 1
}

close(zz)

if ((n %% 16) > 0) {
    for (i in 1:(16 - (n %% 16))) {
        cat("   ")
    }
    cat("  |")
    cat(dum)
    for (i in 1:(16 - (n %% 16))) {
        cat(" ")
    }
    cat("|\n")
    dum = ""
}

cat(sprintf("\nRead %d bytes.", n))
cat("\n")

 

 

실행 예 1> r --silent --slave -q -f testHexView_02.r --args temp_1.bin
The size of the file "temp_1.bin" is 12.

0000 0000:  48 65 6C 6C 6F 20 74 68-65 72 65 0A              |Hello there.    |

Read 12 bytes.

실행 예 2> r --silent --slave -q -f testHexView_02.r --args myFile.ser
The size of the file "myFile.ser" is 130.

0000 0000:  AC ED 00 05 73 72 00 06-50 65 72 73 6F 6E 07 31  |....sr..Person.1|
0000 0010:  46 DB A5 1D 44 AB 02 00-03 49 00 03 61 67 65 4C  |F...D....I..ageL|
0000 0020:  00 09 66 69 72 73 74 4E-61 6D 65 74 00 12 4C 6A  |..firstNamet..Lj|
0000 0030:  61 76 61 2F 6C 61 6E 67-2F 53 74 72 69 6E 67 3B  |ava/lang/String;|
0000 0040:  4C 00 08 6C 61 73 74 4E-61 6D 65 71 00 7E 00 01  |L..lastNameq.~..|
0000 0050:  78 70 00 00 00 13 74 00-05 4A 61 6D 65 73 74 00  |xp....t..Jamest.|
0000 0060:  04 52 79 61 6E 73 71 00-7E 00 00 00 00 00 1E 74  |.Ryansq.~......t|
0000 0070:  00 07 4F 62 69 2D 77 61-6E 74 00 06 4B 65 6E 6F  |..Obi-want..Keno|
0000 0080:  62 69                                            |bi              |

Read 130 bytes.

 

 

Posted by Scripter
,

 

Boo 언어 소스:

#  Filename: testHexView_02.boo
#
#   Execute: booi testHexView_02.boo [filename]
#
#    Or
#
#   Compile: booc testHexView_02.boo
#   Execute: testHexView_02 [filename]
#
# Date: 2013. 8. 16.

import System
import System.IO

def printUsage():
    print "Usage: booi testHexView_02 [filename]"

def isDirectory(path as string) as bool:
    fa = System.IO.File.GetAttributes(path)
    isDir = false
    if (fa & FileAttributes.Directory) != 0:
        isDir = true
    return isDir

def ascii(s as string) as int:
    arr = array(s)
    n = cast(int, arr[0])
    return n

def toChar(n as int) as char:
    a = cast(char, n)
    return a

def toHex(b as int) as string:
    s = ""
    x1 = (b & 0xF0) >> 4
    x2 = b & 0x0F
    if x1 < 10:
        s += toChar(ascii('0') + x1)
    else:
        s += toChar((x1 - 10) + ascii('A'))
    if x2 < 10:
        s += toChar(ascii('0') + x2)
    else:
        s += toChar((x2 - 10) + ascii('A'))
    return s

def toHex8(n as int) as string:
    s = ""
    x1 = (n & 0xF0000000) >> 28
    x2 = (n & 0xF000000) >> 24
    x3 = (n & 0xF00000) >> 20
    x4 = (n & 0xF0000) >> 16
    x5 = (n & 0xF000) >> 12
    x6 = (n & 0xF00) >> 8
    x7 = (n & 0xF0) >> 4
    x8 = n & 0x0F
    if x1 < 10:
        s += toChar(ascii('0') + x1)
    else:
        s += toChar((x1 - 10) + ascii('A'))
    if x2 < 10:
        s += toChar(ascii('0') + x2)
    else:
        s += toChar((x2 - 10) + ascii('A'))
    if x3 < 10:
        s += toChar(ascii('0') + x3)
    else:
        s += toChar((x3 - 10) + ascii('A'))
    if x4 < 10:
        s += toChar(ascii('0') + x4)
    else:
        s += toChar((x4 - 10) + ascii('A'))
    s += ' '
    if x5 < 10:
        s += toChar(ascii('0') + x5)
    else:
        s += toChar((x5 - 10) + ascii('A'))
    if x6 < 10:
        s += toChar(ascii('0') + x6)
    else:
        s += toChar((x6 - 10) + ascii('A'))
    if x7 < 10:
        s += toChar(ascii('0') + x7)
    else:
        s += toChar((x7 - 10) + ascii('A'))
    if x8 < 10:
        s += toChar(ascii('0') + x6)
    else:
        s += toChar((x8 - 10) + ascii('A'))
    return s

if argv.Length < 1:
    printUsage()
    Environment.Exit(1)

filename = argv[0]
if isDirectory(filename):
    Console.WriteLine("The file \"" + filename + "\" is a directory.")
    Environment.Exit(1)

if not File.Exists(filename):
    print "The file \"" + filename + "\" does not exist."
    return

fileSize = FileInfo(filename).Length;
print "The size of the file \"" + filename + "\" is " + fileSize + "."
print

br = BinaryReader(File.Open(filename, FileMode.Open))
dum = ""
n = 0L
while n < fileSize:
    if n % 16 == 0L:
        Console.Write(toHex8(n) + ": ")
    data = br.ReadByte()
    if n % 16 != 8L:
        Console.Write(" ")
    else:
        Console.Write("-")
    Console.Write(toHex(data))

    if (data & 0xFF) >= 0x20 and (data & 0xFF) <= 0x7E:
        dum += toChar(data & 0xFF)
    else:
        dum += "."

    if n > 0 and n % 16 == 15L:
        Console.Write("  |")
        Console.Write(dum)
        Console.Write("|")
        Console.WriteLine()
        dum = ""

    n += 1

if n > 0 and n % 16 > 0:
    for i in range(16 - (n % 16)):
        Console.Write("   ")
    Console.Write("  |")
    Console.Write(dum)
    for i in range(16 - (n % 16)):
        Console.Write(" ")
    Console.Write("|")
    Console.WriteLine()
    dum = ""

Console.WriteLine()
Console.WriteLine("Read " + n + " bytes.")

 

실행 예 1> booi testHexView_02.boo temp_1.bin
The size of the file "temp_1.bin" is 12.

0000 0000:  48 65 6C 6C 6F 20 74 68-65 72 65 0A              |Hello there.    |

Read 12 bytes.

실행 예 2> booi testHexView_02.boo myFile.ser
The size of the file "myFile.ser" is 130.

0000 0000:  AC ED 00 05 73 72 00 06-50 65 72 73 6F 6E 07 31  |....sr..Person.1|
0000 0010:  46 DB A5 1D 44 AB 02 00-03 49 00 03 61 67 65 4C  |F...D....I..ageL|
0000 0020:  00 09 66 69 72 73 74 4E-61 6D 65 74 00 12 4C 6A  |..firstNamet..Lj|
0000 0030:  61 76 61 2F 6C 61 6E 67-2F 53 74 72 69 6E 67 3B  |ava/lang/String;|
0000 0040:  4C 00 08 6C 61 73 74 4E-61 6D 65 71 00 7E 00 01  |L..lastNameq.~..|
0000 0050:  78 70 00 00 00 13 74 00-05 4A 61 6D 65 73 74 00  |xp....t..Jamest.|
0000 0060:  04 52 79 61 6E 73 71 00-7E 00 00 00 00 00 1E 74  |.Ryansq.~......t|
0000 0070:  00 07 4F 62 69 2D 77 61-6E 74 00 06 4B 65 6E 6F  |..Obi-want..Keno|
0000 0080:  62 69                                            |bi              |

Read 130 bytes.

 

 

Posted by Scripter
,