Click here to Skip to main content
14,207,131 members
Rate this:
 
Please Sign up or sign in to vote.
See more:
Hello,
I need to convert float number to byte[] apart from using inbuilt method
BitConverter.GetBytes
. I want to achieve this by using some logic.

Thank you.

What I have tried:

I googled, but was unable to find anything apart from the builtin method
BitConverter.GetBytes

.
Posted
Updated 21-Oct-16 4:21am
Comments
NotPolitcallyCorrect 21-Oct-16 10:15am
   
Try https://msdn.microsoft.com/en-us/library/system.buffer.blockcopy.aspx and you need to seriously improve your google skills.
Suvendu Shekhar Giri 21-Oct-16 10:19am
   
Yes, that should do the job.
but, OP wants to build the logic him/herself. not sure why !
"....apart from using inbuilt method"
NotPolitcallyCorrect 21-Oct-16 10:23am
   
Because his homework said so.
Suvendu Shekhar Giri 21-Oct-16 10:18am
   
so, what is the issue with using built in functions?
is there a special requirement to do so?
partha143 24-Oct-16 0:40am
   
Suvendu, I want to convert float to Byte in Device Description language which is a very simple language and does not poses any inbuilt method to do so. So, my approach was to built this logic first in C# and then try to convert it to Device Description language.

1 solution

Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

That's complicated in C#, because casting doubles to "byte friendly" values in C# isn't possible in "normal" code.
If you have a look at the Reference Sources however, you can see how they do it - and it's pretty simple:
[System.Security.SecuritySafeCritical]  // auto-generated
public unsafe static byte[] GetBytes(double value)
{
    Contract.Ensures(Contract.Result<byte[]>() != null);
    Contract.Ensures(Contract.Result<byte[]>().Length == 8);

    return GetBytes(*(long*)&value);
}

[System.Security.SecuritySafeCritical]  // auto-generated
public unsafe static byte[] GetBytes(long value)
{
    Contract.Ensures(Contract.Result<byte[]>() != null);
    Contract.Ensures(Contract.Result<byte[]>().Length == 8);

    byte[] bytes = new byte[8];
    fixed(byte* b = bytes)
        *((long*)b) = value;
    return bytes;
}
That's the most efficient way to do it (ignore the Contract bits)
But unsafe code may not be what your homework asks for either...
   
Comments
partha143 24-Oct-16 0:42am
   
I want this logic to be implemented in Device Description Language which does not poses implementation of pointers. Can't we implement it avoiding pointers?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Advertise | Privacy | Cookies | Terms of Service
Web03 | 2.8.190612.1 | Last Updated 21 Oct 2016
Copyright © CodeProject, 1999-2019
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100