简体   繁体   中英

How to Convert from byte? to byte[]?

I am trying to convert a byte received from a database query.

EF Core returns nullable tinyint as byte? and I need to convert it to decimal .

Is there any way to convert it OnModelCreating with model builder in the DbContext ?

I am not very familiar with EF Core. So far I only managed to do this - after I already got my object in handler:

decimal? newDecimal = Convert.ToDecimal(BitConverter.ToDouble(AddByteToArray(priceByte), 0)));

private static byte[] AddByteToArray(byte? newByte)
{
    if (newByte != null)
    {
        if(newByte == 0)
        {
            return Enumerable.Repeat((byte)0x0, 8).ToArray();
        }

        byte[] bArray = new byte[1];
        // Not sure how to convert a non null and byte > 0 to byte[]?? As double requires byte[] while the tinyint return byte from the database

        return bArray;
    }

    return null;
}

I think you are getting a little confused by the types here. The DB returns a byte? for a tinyint because a tinyint has only 8 bits of data. But otherwise it is an integer. If you want to convert it to a decimal , you would use the same mechanism as you would to convert an int or a long to a decimal : cast it. You do not want to convert a byte array to a decimal as that will try to interpret the data in the array as a binary representation of a decimal (see my last paragraph). So this code should suffice to do the conversion.

decimal? d = newByte == null ? null : (decimal)newByte; 

See that such a conversion is possible here: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/numeric-conversions

Note the remarks section here that indicates we are dealing with a binary representation of the number, where care must be taken in dealing with endianness, etc.

https://docs.microsoft.com/en-us/dotnet/api/system.bitconverter?view=net-6.0#remarks

Basically, numbers larger than a byte are technically stored as an array of bytes (since all memory is byte addressable in x86) but the interpration of those bytes into a number depends on the type of the number. For floating point numbers especially the structure of data inside the byte array is complex, broken into fields that represent the base, exponent and sign. And those are not always interpreted in a straightforward way. If you just give a byte array with 27 as the first byte, you don't know where that ends up in the several fields that make up the binary representation of a double. It may well work, but probably not.

Instead of

byte[] bArray = new byte[1];

You can use

byte[] bArray = {(byte)newByte};

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