# バイナリー形式

書式モードでコマンド表現されたバイト列をバイナリ形式に変換します。

```
A: [送受信したいデータ]
 ↓↑
B: [コマンド表現 [A: ] ]
 ↓↑
C: 系列Bをアスキー形式またはバイナリ形式に変換
   [形式ヘッダ [B: [A: ] ] 終端]
 ↓↑
マイコンのUART入出力
```

例えば、コマンド表現で 00A01301FF123456 （子機から親機に ACK 付きで 123456 を送信する）をバイナリ形式で表現すると、以下のようになります。

```
0xA5 0x5A 0x80 0x08 0x00 0xA0 0x13 0x01 0xFF 0x12 0x34 0x56 0x3D
```

## 形式の定義

|        | 元データのバイト数 | 表現形式におけるバイト数 | 解説                                                                                                     |
| ------ | --------- | ------------ | ------------------------------------------------------------------------------------------------------ |
| ヘッダ    |           | 2            | 0xA5 0x5A を指定します。                                                                                      |
| データ長   |           | 2            | <p>データ長はビッグエンディアン形式の２バイトで、MSB (0x8000) を設定した上、データ部の長さを指定します。<br>例えばデータ部の長さが 8 バイトなら 0x8008 を指定します。</p> |
| データ部   | N         | N            | 元データを指定します。                                                                                            |
| チェックサム |           | 1            | <p>データ部の各バイトの XOR を計算します。<br>例えばデータ部が 00A01301FF123456 なら 0x00 xor 0xA0 xor ... 0x56 = 0x3D となります。</p> |
| フッタ    |           | (1)          | チェックサムが事実上の終端です。無線モジュールからの出力では 0x04 (EOT) が付加されます。                                                     |

## 使ってみる

バイナリ形式の確認は一般に難易度が高く、上手くコマンドが入力できない場合の分析が非常に困難です。マイコンなどでデバッグされるのに先立って、PCなど確認しやすい環境で予め実行しておくことを強くお勧めします。

{% content-ref url="/pages/-Mk6ZiMbRi9ymbpcvgrX" %}
[バイナリー形式で使ってみる](/mw-pug-uart/mode_selection/mode_ab/binary-format/try-to-use-the-binary-format.md)
{% endcontent-ref %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://twelite.gitbook.io/mw-pug-uart/mode_selection/mode_ab/binary-format.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
