Click here to Skip to main content
15,881,709 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,
I need to convert float number to byte[] apart from using inbuilt method
C#
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
C#
BitConverter.GetBytes

.
Posted
Updated 21-Oct-16 4:21am
Comments
[no name] 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"
[no name] 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

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:
C#
[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);
}

C#
[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...
 
Share this answer
 
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)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900