1

byte[6]数値をinに変換する最良の方法は何C#ですか?

MagTek Card readerデバイス画面に目的の金額を使用して表示しようとしていますが、6-byte配列である必要があります。金額を使用して承認する必要があります, EMV Tag 9F02, format n12.

関数:

 int requestSmartCard(int cardType, int comfirmationTime, int pinEnteringTime, int beepTones, int option, byte [] amount, int transactionType, byte[] cashback, byte [] reserved);

amount パラメータの説明は次のとおりです。 - amount 使用および承認される金額、EMV タグ 9F02、フォーマット n12。これは 6 バイトの配列でなければなりません。

編集:

これは、C# での例のコード例です。

          byte []amount = new byte[6];
          amount[3] = 1;
          byte []cashBack = new byte[6];

          PrintMsg(String.format("start a emv transaction"));
          byte reserved[]  = new byte[26];

          byte cardType = 2;
          byte confirmWaitTime = 20;
          byte pinWaitTime = 20;
          byte tone = 1;
          byte option = 0;
          byte transType = 4;
          retCode = m_MTSCRA.requestSmartCard(cardType, confirmWaitTime, pinWaitTime, tone, option, amount, transType, cashBack, reserved);

その後、デバイスの画面に 100.00 $ の金額が表示されます。

編集: 質問形式の float を byte[6] から number から byte[6] に変更しました。

4

2 に答える 2

3

メソッドは次のようになります。

public static byte[] NumberToByteArray(float f, int decimals)
{
    // A string in the format 0000000000.00 for example
    string format = new string('0', 12 - decimals) + "." + new string('0', decimals);

    // We format the number f, removing the decimal separator
    string str = f.ToString(format, CultureInfo.InvariantCulture).Replace(".", string.Empty);

    if (str.Length != 12)
    {
        throw new ArgumentException("f");
    }

    var bytes = new byte[6];

    for (int i = 0; i < 6; i++)
    {
        // For each group of two digits, the first one is shifted by
        // 4 binary places
        int digit1 = str[i * 2] - '0';
        bytes[i] = (byte)(digit1 << 4);

        // And the second digit is "added" with the logical | (or)
        int digit2 = str[(i * 2) + 1] - '0';
        bytes[i] |= (byte)digit2;
    }

    return bytes;
}

(1) 最適化された方法ではないことに注意してください。代わりに掛けることもできまし10^decimalsたが、無駄な掛け算はしたくありません。

注 (2) は実際には使用しないでくださいfloatfloat(運が良ければ) 6 桁または 7 桁の精度を持ちますが、その形式は 12 桁を格納できます。doubleまたはさらに良いを使用してくださいdecimal。に置き換えるfloatdecimal、正しく機能します。

注 (3) 使用する小数点以下の桁数が必要です。ユーロまたはドルの場合は 2 ですが、他の通貨の場合は異なる場合があります。

注 (4) 数値から BCD への変換の問題です。紐を通さなくても作れます。それをするのが面倒です (そして で乗算を実行したくありませんfloat)

于 2015-06-17T10:40:23.073 に答える