Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am developing a windows forms application. I have a double value 1.5.That value I need to convert into a two byte array. But when I am converting using BitConverter.GetBytes, getting 8 bytes of data. Please refer my code below.
double d = 1.5;
byte[] array = BitConverter.GetBytes(d);
Double is 8 byte value, so if you have an arbitrary double there's no hope for you; however, if you have some restrictions, e.g. the value is in the [0..100] range and has at most 2 digits after the decimal point, you can encode it:
// presuming source in [0..100] with at most 2 digit after decimal point
double source = 1.5;
// short is 2 byte value
short encoded = (short) (source * 100 + 0.5);
byte[] array = BitConvertor.GetBytes(encoded);
// decode back to double
double decoded = encoded / 100.0;
A double is a 64 bit value that just so happens to be 8 bytes. There's nothing that can be done about this.
A double is 8 bytes in length, so unless you want a specific sub-array out of the 8 you're getting (you probably don't), then this is the wrong way to go about it.
You can cast your variable to a single-precision float. That will of course lose some precision, but you will get 4 bytes instead of 8.
If this is still unacceptable, you need to have an implementation of a half-precision float, which sadly doesn't come out-of-the-box with .NET.
I found an implementation here:
http://sourceforge.net/p/csharp-half/code/HEAD/tree/System.Half
You can use it like this:
var half = (Half)yourDouble;
var bytes = Half.GetBytes(half); // 2 bytes
Related
This question already has answers here:
How do I convert an array of floats to a byte[] and back?
(4 answers)
Closed 1 year ago.
I want to convert 794.328247 value to byte.
I used Convert.ToByte(794.328247) but it showing following error,
Error : - Value was either too large or too small for an unsigned byte.
So anyone can help me to resolve this issue.
Thanks.
You probably want Bitconverter.GetBytes
byte[ ] byteArray = BitConverter.GetBytes( 794.328247);
Note that this produce an array of bytes since a float is 32bit, so it needs 4 bytes to store it. Do the reverse with ToSingle.
The alternative is to truncate the float: var b = (byte) 794.328247;, but this is usually not a good idea since a byte has a far smaller range of values that a float. In some cases you might need to first normalize the input value to some range of values before truncating. I.e. you would remap values from say 750-800 to the 0-255 range.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
If I have an int equal to 8675309 what would be the best/quickest way to convert that into a float equal to 0.8675309f?
Examples:
input as an int: 8675309
output as a float: 0.8675309
input as an int: 4234512
output as a float: 0.4234512
input as an int: 56
output as a float: 0.56
input as an int: 123456
output as a float: 0.123456
input as an int: 654321
output as a float: 0.654321
I've tried mapping the outputs to a value between 0 and 1, but for an RNG setup it tends to have an average of .64 which isn't ideal.
I've used Tanh, Cos, Sin, and other functions to get it mapped, but it seems as though I'm really only wanting to get the exact number with a decimal at the beginning of it so the accuracy stays the same.
I could divide by a large number I suppose, but it wouldn't be consistent as the size of the number would have to change as the RNG output changed in size.
I really don't know why this doesn't have enough information in it. In the first line it is clear what EXACTLY I am looking to do. How can someone be more specific than that?
The way you'd do this on paper is:
Find the number of digits in 8675309
Divide by 10^(number of digits)
You can find the number of digits when written as base 10 either by formatting it as a string and counting the characters (bad), or by taking the log to the base 10 and rounding it up (good):
int input = 8675309;
int numDigits = (int)Math.Ceiling(Math.Log10(input));
Then divide this by 10^numDigits:
float result = input / MathF.Pow(10, numDigits);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Problem:
I am trying to convert a byte[] to a single. I've tried using BitConverter.ToSingle() and it doesn't give the desired result.
The Content of the Array is:
0
0
0
100
The desired output is 100; I know an Int would work for this but I just choose that number for easy debugging. I have also tried moving the 100 into every possible position in the array, with no luck.
My output always looks like 9.3345534545E
or something similar with different digits.
Any Ideas?
IEE-754 types (Single and Double - float and double in C#) do not have a trivial binary representation so 0x00 0x00 0x00 0x64 does not represent the value of 0x64 (100 in decimal).
The actual raw, binary representation of IEEE-754 values is rather complicated and setting them and performing the conversion from integer to IEE-754 really isn't worth the effort (unless it's a learning exercise). It's best to let the library/platform or even the processor do it for you:
Because your value is an integer value, you need to convert it into Int32 first, and then use the Convert class (or a simple compiler cast which will perform the type conversion under-the-hood).
Int32 val = BitConverter.ToInt32( yourArray ); // assuming it's little-endian
Single s1 = (Single)val;
Single s2 = Convert.ToSingle( val );
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Hi I need to read an int from excel cell and send it in one byte but when I do it with this code:
cert1 = Encoding.Default.GetBytes(
"write" + flg +
dataRow[3].ToString() +
dataRow[4].ToString() +
dataRow[5].ToString().Substring(0,4) +
dataRow[5].ToString().Substring(5,2) +
dataRow[5].ToString().Substring(8,2) +
dataRow[6].ToString() +
dataRow[7].ToString() +
dataRow[8].ToString() +
dataRow[10].ToString().Substring(0, 4) +
dataRow[10].ToString().Substring(5, 2) +
dataRow[10].ToString().Substring(8, 2) +
dataRow[11].ToString());
comport.Write(cert1, 0, cert1.Length);
and debug it, I get two byte for number 12 which in excel cell. It means it thinks 12 as string and returns 1 as one byte and 2 as another. I assume I need to use this Int.Parse() to look at 12 as one int and convert it to binary and after that to byte.
Am I right? If yes how to do it? Thanks
you are getting the bytes from the characters not the ints
for example if you have dataRow[3] = 12
then in your case you will get the bytes for 1 and 2 as you saw.
you need to use
BitConverter.GetBytes(Int.Parse(dataRow[3].ToString()));
for the field
so you have to do this for all the fields and then combine the arrays.
you can use System.Buffer.BlockCopy for that.
in this article there are some examples how to do that
I think that the conversion Byte.Parse() is probably what you are looking for: http://msdn.microsoft.com/en-us/library/4eszwye3.aspx
If you call GetBytes for string 12 you're going to get two bytes: '1' and and '2'. If you want to get a byte with value 12, the you have to convert the string to integer first and then get the bytes of it. There are different ways to parse an integer from a string (int.Parse() or int.TryParse() are two of them).
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I had asked a question about converting COMP fields, for which I did not get any answer.
I hope stack-overflow can help me on this question.
I succeeded in converting COMP-3 to decimal. I need your help in converting the unpacked decimal back to COMP-3, in any high level programming language, but preferably in Java or c#.net.
In packed decimal -123 is represented as X'123d' (the last nyble c,d or f being the sign).
One of the simplest ways to handle packed decimal is to simply convert the bytes
to a hex string (or vice versa as required) then use normal string manipulation. This may not be the most efficient but it is easy to implement.
So to convert a Integer (value) to packed decimal is roughly (note: I have not tested the code)
String sign = "c";
if (value < 0) {
sign = "d";
value = -1 * value;
}
String val = value + "d"
byte[] comp3Bytes = new BigInteger(val, 16).toByteArray();
Following are some example code for converting to/from comp3
To retrieve a packed decimal from an array of bytes see method getMainframePackedDecimal
in http://record-editor.svn.sourceforge.net/viewvc/record-editor/Source/JRecord/src/net/sf/JRecord/Common/Conversion.java?revision=3&view=markup
and to set a packed decimal see
setField in http://record-editor.svn.sourceforge.net/viewvc/record-editor/Source/JRecord/src/net/sf/JRecord/Types/TypePackedDecimal.java?revision=3&view=markup
both routines take an array of bytes, a start position and either a length of a field position.
There are other examples of doing this on the web (JRanch I think has code for doing the conversion as well), do a bit of googling.
Converting zoned decimal to comp-3 is quite easy -- flip the nibbles of the low byte and strip off the high nibble of all other bytes.
Consider the number 12345 -- in packed decimal notation, that would be a x'12345C' or x'12345F' (both C and F are +, A B and D are -). When you converted it to zoned decimal, you flipped the low nibble and inserted a "F" in the high nibble between each digit. Turning it into x'F1F2F3F4C5'.
To convert it back, you just reverse the process. Using java, that would look like:
byte[] myDecimal = { 0xF1, 0xF2, 0xF3, 0xF4, 0xF5 };
byte[] myPacked = new byte[3];
//Even low nibble moved to high nibble and merged with odd low nibble
myPacked[0] = ((myDecimal[0] & 0b00001111) << 4)) | (myDecimal[1] & 0b00001111);
myPacked[1] = ((myDecimal[2] & 0b00001111) << 4)) | (myDecimal[3] & 0b00001111);
//Last byte gets filpped for sign
myPacked[2] = ((myDecimal[5] & 0b00001111) << 4)) | (myDecimal[4] & 0b00001111);
When I have messed with COMP-3 in the past with Java I ended up writing a method to read in the bytes and convert them to a number. I don't think I ever had to write COMP-3 out, but I assume I would use the same logic in reverse.