最短16進ダンププログラム


13

チャレンジ

ファイルの各バイトを表示するコンソールプログラムを作成します。


勝ち

これは、バイト数が最も少なくなります。


ルール

  • プログラムはコンソールアプリケーションである必要があります。つまり、何らかのコマンドラインインタープリターから実行されます。
  • 各バイトは、スペースで区切られた大文字の16進数でなければならず、2桁でなければなりません。(1桁の場合は、その前に番号0を入れます)
  • ファイル、IOまたは代替を使用して読み取る必要があり、ハードコードされていません。
  • ファイルパスは、コマンドライン引数またはユーザープロンプト(STDINなど)として指定する必要があります
  • 抜け穴はありませんしてください

test.txt(LFで終わる)

Hello World!

$ ./hexdump.exe test.txt
48 65 6C 6C 6F 20 57 6F 72 6C 64 21 0A

16
@ facepalm42 facepalmを避けるために、Sandboxを使用して投稿する前に将来の課題を設計することを強くお勧めします。
アダム

2
画面に収まらない場合、すべてのバイト値を一度に表示するにはどうすればよいですか?スクロールは明らかに「一度に」ではありません。また、値を返すだけの(関数)の何が問題になっていますか?
アダム

7
@ facepalm42チャレンジを投稿してから長い間、仕様を変更しないでください。元の投稿では16進数の正確な形式を指定していなかったため、回答者に任せていました。最新の編集により、既存の回答が無効になりました!
アダム

11
コマンドライン引数またはユーザープロンプトのみを許可する特別な理由はありますか?たとえば、ファイル名を関数の引数として使用することの何が問題になっていますか?
アダム

3
入力hello.txtとしての例として単純なテキストファイルがあり、予想される出力がどうあるべきかが役立ちます。たとえば、が単に改行を含む単語を含む場合、これは出力でどのように表現されますか?バイトを16ビット、32ビット、または64ビットのワードにグループ化していますか?または、各バイトは2桁の16進数で表されますか?各バイトを16進数として、または各xビットワードの後に​​スペースを使用できますか?各バイトに接頭辞が必要ですか?hello.txthello0x
ショーンビーバーズ

回答:



6

ルビー、26バイト

$<.bytes{|b|$><<"%02X "%b}

オンラインでお試しください!


これは、プログラム引数としてファイルパスを指定してファイルの内容を読み取りますか?TIOに基づくと、STDINから読み取ったように見えますが、Rubyが間違っていると言うほど十分に知りません。
ケビンCruijssen

1
@KevinCruijssenはい、プログラムの引数としてファイルパスを使用します。引数がない場合は、$<代わりにSTDINからの読み取りに切り替えます。
バリューインク


6

Java 11、156 154バイト

import java.nio.file.*;interface M{static void main(String[]a)throws Exception{for(int b:Files.readAllBytes(Path.of(a[0])))System.out.printf("%02X ",b);}}

@Holgerのおかげで-2バイト

を使用してオンラインで試してください./.input.tio引数としてfile-pathしは、file-contentとして指定された入力を持ちます。

説明:

import java.nio.file.*;        // Required import for Files and Paths
interface M{                   // Class
  static void main(String[]a)  //  Mandatory main method
      throws Exception{        //  With mandatory thrown clause for the readAllBytes builtin
                                         a[0]    // Get the first argument
                                 Path.of(    )   // Get the file using that argument as path
              Files.readAllBytes(             )  // Get all bytes from this file
    for(int b:                                 ) // Loop over each of them:
      System.out.printf(                         //  And print the current byte
                        "%02X ",b);}}            //  As uppercase hexadecimal with leading 0
                                                 //  and trailing space as delimiter

interface代わりに使用する理由はclass何ですか?
JakeDot

4
@JakeDot mainはパブリックである必要があり、インターフェイスメソッドは常にパブリックでinterfaceあり、class+ よりも短くなっていpublicます。
グリムミー

3
Java 11では、Path.of代わりに使用できますPaths.get
Holger

1
@ホルガーありがとう!:)
ケビンクルーッセン

2
@GrimyはJava 9以降、インターフェイスメソッドは常にpublicではありませんが、public明示的に宣言されていない限りそうprivateです。
ホルガー

6

PHP60 59 54バイト

<?=wordwrap(bin2hex(implode(file($argv[1]))),2,' ',1);
  • -1バイト、manassehkatzに感謝
  • ブラックホールのおかげで-5バイト

オンラインでお試しください!


1
末尾を削除して?>2バイトを保存できるか、またはそれが機能しない場合?>はセミコロンに置き換えて1バイトを保存する必要があります。
manassehkatz-Moving 2 Codidact

2
(-4バイト)のimplode(file($x))代わりに使用しfile_get_contents($x)ます。
ブラックホール

2
そしてwordwrap()1最後のパラメーターとして、はよりも1バイト短くなりchunk_split()ます。
ブラックホール


4

APL(Dyalog Unicode)、16バイト

匿名の暗黙の接頭辞関数。上の行に10進数の0〜15で表される上位4ビットと、同様に下の行に表される下位4ビットの2行の行列を返します(値が消費されない場合は暗黙的に出力します)。つまり、マトリックスにはファイルのバイト数と同じ数の列があります。

16 1683 ¯1∘⎕MAP

オンラインでお試しください!

⎕MAP 引数filenameを
 パラメーター付きの配列にマップします。ファイルの
¯1 全長が
83 8ビット整数として読み取られます

16 16⊤ (アンチベース)を2桁の16進数に変換します


1
@ facepalm42非常に16進数です。たとえばH、72は4×16¹+ 8×16⁰または[4,8]₁₆です。したがって、例の最初の列はになります[4,8]
アダム

ああ、私は完全に忘れました!ごめんなさい。
facepalm42

4

Python 3、59バイト

Mostly Harmlessのおかげで-11バイト!

James K Polkのおかげで-8バイト!

Blueのおかげで-24バイト!

print(' '.join('%02X'%ord(i)for i in open(input()).read()))

オンラインでお試しください!

これは非常に簡単です。STDINで入力として指定されたファイル名を開き、それを読み取り、各文字をASCII値に変換し、各数値を16進数に変換し"0x"、Pythonで16進数値に先行するものを取り除き、必要に応じて値にゼロを埋め込み、値を結合しますスペースと一緒に。


'%02X'%ord(i)16進数の出力をスライスする代わりに数バイトを節約できる
ほとんど無害

@MostlyHarmless完了!-11バイト。ありがとう!
mprogrammer

「%02x」の代わりに「%02X」はどうでしょうか?.upper()
ジェームズムーヴンポーク大統領

代わりにファイル名としてimport sys使用することで、からバイトを保存できraw_input()ます。ルールにより、ユーザープロンプトが許可されます。
ブルー

@ブルーありがとう!そして、それはあなたがちょうどできるPython 3ではさらに短くなりますinput()
-mprogrammer

3

バッシュ 33  23バイト

...多くの助けを借りて:
-3 マナトワークに
感謝-4 飛び出しに
感謝-3 Nahuel Fouilleulに感謝

echo `xxd -c1 -p -u $1`

オンラインでお試しください!

用途入力上記TIOリンクその注-私たちは、ローカルにファイルを書き込むことができますので、このショーは、ファイルのパスを取るプログラムとして活躍します。


軽微な削減:xxd -u -p $1|fold -2|tr \\n \
マナトワーク

おかげで、「this」リンクバージョンを取得して動作させる方法は\nあり\ ますか?編集:別のエスケープ文字を追加しました。
ジョナサンアラン

正しく理解できたら、二重引用符から単一引用符に変更するだけです。オンラインで試してみてください。
マナトワーク

素晴らしいありがとう!
ジョナサンアラン

xxd -c1 -p -u $1|tr \\n \
飛び出した

3

Kotlin130の 127 104 93 92バイト

fun main(a:Array<String>){java.io.File(a[0]).readBytes().forEach{print("%02X ".format(it))}}

オンラインでお試しください!

編集:@ChrisPartonのおかげで-11バイト

編集:ワーキングTIO

編集:@KevinCruijssenのおかげで-1バイト


1
インポートと参照を捨てることができFilejava.io.File代わりに?
クリスパートン

@ChrisParton右、ありがとう!
クイン

ここで働くTIO。./.input.tioファイルパス引数として使用でき、ファイルコンテンツとしてSTDINを使用します。:)
ケビンクルーッセン

@KevinCruijssenありがとう!ちょうど更新された答え
クイン

1
Kotlinはわかりませんが、でスペースを削除してもTIOは動作a:Arrayします。したがって、バイトを節約できると思います。
ケビンCruijssen

2

Dart140 134バイト

import'dart:io';main(a){print(new File(a[0]).readAsBytesSync().map((n)=>n.toRadixString(16).toUpperCase().padLeft(2,'0')).join(' '));}

オンラインでお試しください!

変数名を減らすのを忘れたため、-6バイト


ダーツの場合は+1。そのような過小評価された言語。
vasilescur

それは基本的に非常に緩いタイプのシステムのないJSであるため、ゴルフをするのが難しい
エルカン

2

Haskell、145 143バイト

import System.Environment
import Text.Printf
import Data.ByteString
main=getArgs>>=Data.ByteString.readFile.(!!0)>>=mapM_(printf"%02X ").unpack

1
もう少し短く:import Data.ByteStringプラスmain=getArgs>>=Data.ByteString.readFile.(!!0)>>=mapM_(printf"%02X ").unpack
nimi

2

Rust、141バイト(投稿版)

use std::{io::*,fs::*,env::*};fn main(){for x in File::open(args().nth(1).unwrap()).unwrap().bytes(){print!("{:02X} ",x.unwrap())}println!()}

Rust、151バイト(オリジナルバージョン)

fn main(){std::io::Read::bytes(std::fs::File::open(std::env::args().nth(1).unwrap()).unwrap()).map(|x|print!("{:02X} ",x.unwrap())).count();println!()}

-10バイト:TIO
ハーマンL

2

bash + Stax、6 + 4 + 1 = 11バイト

これは、この時点での完全な理論作成です。これを実際に実行することはできません。すべてが仕様どおりに機能する場合、これは機能しますが、すべてが機能するわけではありません。

bashスクリプトは

]<$1

staxプログラムをコンパイルして、]に保存する必要があります

╛↕ßú┼_

文字セットをISO 8859-1に設定します(Windows-1252はここでは動作しません)。

開梱および説明

_          push all input as a single array
F          run the rest of the program for each element of the array
 |H        write the hex of the byte to standard output
 |         write a space to standard output

2

絵文字コード186 162バイト

📦files🏠🏁🍇🔂b🍺📇🐇📄🆕🔡👂🏼❗️❗️🍇👄📫🍪🔪🔡🔢b❗️➕256 16❗️1 2❗️🔤 🔤🍪❗️❗️🍉🍉

こちらからオンラインでお試しください

非ゴルフ:

📦 files 🏠  💭 Import the files package into the default namespace
🏁 🍇  💭 Main code block
🔂 b  💭 For each b in ...
  🍺  💭 (ignoring IO errors)
  📇 🐇 📄  💭 ... the byte representation of the file ...
  🆕 🔡 👂🏼  💭 ... read from user input:
  ❗️ ❗️ 🍇
    👄  💭 Print ...
    📫  💭 ... in upper case (numbers in bases > 10 are in lower case) ...
    🍪  💭 ... the concatenation of:
      🔪 🔡 🔢 b ❗️ ➕ 256  💭 b + 256 (this gives the leading zero in case the hex representation of b is a single digit) ...
              16  💭 ... represented in hexadecimal ...
           ❗️
         1 2  💭 ... without the leading one,
      ❗️
      🔤 🔤  💭 ... and a space
    🍪
    ❗️❗️
  🍉
🍉

2

Perl 6、45バイト

@*ARGS[0].IO.slurp(:bin).list.fmt('%02X').say

オンラインでお試しください!

  • @*ARGS[0] 最初のコマンドライン引数です。
  • .IO(推定)ファイル名をIO::Pathオブジェクトに変換します。
  • .slurp(:bin)ファイル全体Bufをバイトのバッファに読み込みます。(:binファイルの内容はUnicode文字列として返されません。)
  • .list バッファからバイト値のリストを返します。
  • .fmt('%02X')は、List指定されたフォーマット文字列を使用してリストの要素をフォーマットし、それらをスペースで結合するメソッドです。(便利!)
  • .say その文字列を出力します。

Pythonの答えに基づいて、TIOリンクは実際に非常に可能です。
Draco18sは、

いくつかの再配置.listにより41バイトを
ジョーキング



1

ラケット、144バイト

この送信では、末尾のスペースが出力され、末尾の改行は出力されません。これが抜け穴と見なされるかどうかを教えてください:)

(command-line #:args(f)(for([b(call-with-input-file f port->bytes)])(printf"~a "(string-upcase(~r b #:base 16 #:min-width 2 #:pad-string"0")))))

クリーンアップ

(command-line #:args (f)
 (for ([b (call-with-input-file f port->bytes)])
   (printf "~a "
           (string-upcase
            (~r b #:base 16 #:min-width 2 #:pad-string "0")))))

1

Forth(gforth)、71バイト

: f slurp-file hex 0 do dup c@ 0 <# # # #> type space 1+ loop ;
1 arg f

オンラインでお試しください!

TIOは3 arg、コードを渡す前にコマンドラインパーサーに「-e bye」を渡すため、最後の行にあります

コードの説明

: f             \ start a function definition
  slurp-file    \ open the file indicated by the string on top of the stack,
                \ then put its contents  in a new string on top of the stack
  hex           \ set the interpreter to base 16
  0 do          \ loop from 0 to file-length - 1 (inclusive)
    dup c@      \ get the character value from the address on top of the stack
    0 <# # # #> \ convert to a double-length number then convert to a string of length 2
    type        \ output the created string 
    space       \ output a space 
    1+          \ add 1 to the current address value
  loop          \ end the loop
;               \ end the word definition
1 arg f         \ get the filename from the first command-line argument and call the function

1

Javascript、155バイト

for(b=WScript,a=new ActiveXObject("Scripting.FileSystemObject").OpenTextFile(b.Arguments(0));;b.echo(('0'+a.read(1).charCodeAt(0).toString(16)).slice(-2)))

1

VBScript、143バイト

set a=CreateObject("Scripting.FileSystemObject").OpenTextFile(WScript.Arguments(0)):while 1 WScript.echo(right("0"+Hex(Asc(a.read(1))),2)):wend

1

Wolfram言語(Mathematica)94 89バイト

Print@ToUpperCase@StringRiffle@IntegerString[BinaryReadList@Last@$ScriptCommandLine,16,2]

オンラインでお試しください!

コマンド名が長いため、コードは一目瞭然です。ほとんど右から左に読む必要があります。

$ScriptCommandLine       is a list of {scriptname, commandlinearg1, commandlinearg2, ...}
Last@...                 extracts the last command-line argument
BinaryReadList@...       reads the named file into a list of bytes
IntegerString[...,16,2]  converts each byte to a 2-digit hex string (lowercase)
StringRiffle@...         converts this list of strings into a single string with spaces
ToUpperCase@...          converts the string to uppercase
Print@...                prints the result to stdout

1

Gema, 45 characters

?=@fill-right{00;@radix{10;16;@char-int{?}}} 

Sample run:

bash-5.0$ gema '?=@fill-right{00;@radix{10;16;@char-int{?}}} ' <<< 'Hello World!'
48 65 6C 6C 6F 20 57 6F 72 6C 64 21 0A 

Try it online!


1

Pyth, 12 bytes

jdcr1.Hjb'w2

Try it online!

Takes input as user prompt (no way to access command-line arguments AFAIK).

jd           # join on spaces
  c        2 # chop into pieces of length 2
   r1        # convert to uppercase
     .H      # convert to hex string, interpreting as base 256 (*)
       jb    # join on newlines
         '   # read file as list of lines
          w  # input()

(*) I'm not 100% sure if this is intended, but one base 256 digit (as in, one character), will always convert into exactly 2 hex digits, eliminating the need to pad with zeroes.


1

Node.js, 118 bytes

console.log([...require("fs").readFileSync(process.argv[2])].map(y=>(y<16?0:"")+y.toString(16).toUpperCase()).join` `)

What the result looks like: enter image description here

Btw the content of test.txt in the example is as follows:

做乜嘢要輸出大楷姐,搞到要加番toUpperCase()去轉番,咁就13byte啦。

(Why on earth is upper-case output necessary. I had to add the conversion with toUpperCase(), and that cost 13 bytes.)


0

C# .NET Framework 4.7.2 - 235 213 203 191 175 140 bytes

Try it online!

using System.IO;class P{static void Main(string[]a){foreach(var b in File.ReadAllBytes(a[0])){System.Console.Write(b.ToString("X2")+" ");}}}

using System;
using System.IO;

namespace hexdump
{
    class Program
    {
        static void Main(string[] args)
        {
            // Read the bytes of the file
            byte[] bytes = File.ReadAllBytes(args[0]);

            // Loop through all the bytes and show them
            foreach (byte b in bytes)
            {
                // Show the byte converted to hexadecimal
                Console.Write(b.ToString("X2") + " ");
            }
        }
    }
}

1
I think the following will save some bytes (now 181 I think): using System.IO;class P{static void Main(string[] a){if(a.Length>0 && File.Exists(a[0])){foreach(var b in File.ReadAllBytes(a[0])){System.Console.Write($"{b.ToString("X2")} ");}}}}
PmanAce

@PmanAce If you remove some of the whitespace, it gets down to 175.
facepalm42

0

05AB1E, 18 bytes

IvyÇh2j' 0.:' Jvy?

Try it online!

Explanation:

IvyÇh2j' 0.:' Jvy?
Iv                 Loop through each character in input
  y                Push current character
   Ç               ASCII value
    h              Convert to hexadecimal
     2j            Pad with at least 2 spaces
       ' 0.:       Replace all spaces with 0s
            ' J    Add space to end
               vy? Convert to string and print
IvyÇh2j' 0.:' Jvy?
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.