简体   繁体   English

将金额转换为4字节数组

[英]Converting an amount to a 4 byte array

I haven't ever had to deal with this before. 我以前从来没有处理过。 I need to convert a sale amount (48.58) to a 4 byte array and use network byte order. 我需要将销售金额(48.58)转换为4字节数组,并使用网络字节顺序。 The code below is how I am doing it, but it is wrong and I am not understanding why. 下面的代码是我的操作方式,但这是错误的,我不理解为什么。 Can anyone help? 有人可以帮忙吗?

float saleamount = 48.58F; 
byte[] data2 = BitConverter.GetBytes(saleamount).Reverse().ToArray();

What I am getting is 66 66 81 236 in the array. 我得到的是数组中的66 66 81 236。 I am not certain what it should be though. 我不确定应该是什么。 I am interfacing with a credit card terminal and need to send the amount in "4 bytes, fixed length, max value is 0xffffffff, use network byte order" 我与信用卡终端连接,需要以“ 4字节,固定长度,最大值为0xffffffff,使用网络字节顺序”发送金额

Network byte order pseudo-synonym of big-endian, hence (as itsme86 mentioned already) so you can check BitConverter.IsLittleEndian: 因此,网络字节顺序是big-endian的伪同义词(如itsme86所述),因此您可以检查BitConverter.IsLittleEndian:

        float saleamount = 48.58F;
        byte[] data2 = BitConverter.IsLittleEndian
            ? BitConverter.GetBytes(saleamount).Reverse().ToArray()
            : BitConverter.GetBytes(saleamount);

But if you don't know this, probably you already using some protocol, which handle it. 但是,如果您不知道这一点,则可能您已经在使用某种协议来对其进行处理。

The first question you should ask is, "What data type?" 您应该问的第一个问题是“什么数据类型?” IEEE single-precision float? IEEE单精度浮点数? Twos-complement integer? 二进制补码? It's an integer, what is the implied scale? 这是一个整数,隐含的比例是多少? Is $48.53 represented as 4,853 or 485,300 ? 48.53美元代表4,853还是485,300吗?

It's not uncommon for monetary values to be represented by an integer with an implied scale of either +2 or +4. 货币值通常由隐含的+2或+4的整数表示。 In your example, $48.58 would be represented as the integer value 4858 or 0x000012FA . 在您的示例中,$ 48.58将表示为整数值48580x000012FA

Once you've established what they actually want...use an endian-aware BitConverter or BinaryWriter to create it. 一旦确定了他们的实际需求,就可以使用支持endian的BitConverter或BinaryWriter来创建它。 Jon Skeet's MiscUtil , for instance offers: 例如, 乔恩·斯基特(Jon Skeet)的MiscUtil提供:

  • EndianBinaryReader
  • EndianBinaryWriter
  • BigEndianBitConverter
  • LittleEndianBitConverter

There are other implementations out there as well. 还有其他实现。 See my answer to the question " Helpful byte array extensions to handle BigEndian data " for links to some. 请参阅我对“ 有用的字节数组扩展来处理BigEndian数据 ”问题的回答,以获取指向某些链接的信息。

Code you don't write it code you don't have to maintain. 您无需编写的代码无需维护的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM