简体   繁体   中英

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. 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. 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"

Network byte order pseudo-synonym of big-endian, hence (as itsme86 mentioned already) so you can check 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? Twos-complement integer? It's an integer, what is the implied scale? Is $48.53 represented as 4,853 or 485,300 ?

It's not uncommon for monetary values to be represented by an integer with an implied scale of either +2 or +4. In your example, $48.58 would be represented as the integer value 4858 or 0x000012FA .

Once you've established what they actually want...use an endian-aware BitConverter or BinaryWriter to create it. Jon Skeet's MiscUtil , for instance offers:

  • 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.

Code you don't write it code you don't have to maintain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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