I have a 4 byte hex number:
08fdc941
it should be convrted to a float number: 25.25, but I don't know how? I use C#
what is the correct way of converting from hex to float?
From this page on MSDN "How to: Convert Between Hexadecimal Strings and Numeric Types (C# Programming Guide)".
string hexString = "43480170";
uint num = uint.Parse(hexString, System.Globalization.NumberStyles.AllowHexSpecifier);
byte[] floatVals = BitConverter.GetBytes(num);
float f = BitConverter.ToSingle(floatVals, 0);
Console.WriteLine("float convert = {0}", f);
// Output: 200.0056
Something like this:
byte[] bytes = BitConverter.GetBytes(0x08fdc941);
if (BitConverter.IsLittleEndian)
{
bytes = bytes.Reverse().ToArray();
}
float myFloat = BitConverter.ToSingle(bytes, 0);
This yields 25.24855, which is what I think you were looking for.
var bytes = BitConverter.GetBytes(0x08fdc941);
Array.Reverse(bytes);
var result = BitConverter.ToSingle(bytes, 0);
Are you sure it's the right way around, since BitConverter.ToSingle(BitConverter.GetBytes(0x08fdc941).Reverse().ToArray(), 0) is close.
Edit:
Incidentally, http://en.wikipedia.org/wiki/Single_precision_floating-point_format gives a pretty good summary of how ISO/IEC/IEEE 60559 (IEEE 754) single-precision floating-point numbers work.
string hexString = 08fdc941;
Int32 IntRep = Int32.Parse(hexString, NumberStyles.AllowHexSpecifier);
// Integer to Byte[] and presenting it for float conversion
float myFloat = BitConverter.ToSingle(BitConverter.GetBytes(IntRep), 0);
// There you go
return myFloat;
For more information, see this:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/how-to-convert-between-hexadecimal-strings-and-numeric-types
Related
When I launch this console application I get 0, instead of 32 bit string. It throws no error, however.
static void Main()
{
double num = 2.75;
byte [] bytes = BitConverter.GetBytes(num);
int toInt = BitConverter.ToInt32(bytes, 0);
string bitString = Convert.ToString(toInt);
Console.WriteLine(bitString);
}
double is 64 bits.
You're looking at the top 32 bits, which are all zero.
You want float (or call ToInt64 to see all of the bits).
The following code is a work-in-progress that I am also taking time with to try and learn some more about converting between bits, hex, and Int;
A lot of this is obviously repetitive operations since we're doing the same thing to 7 different "packages," so feel free to gloss over the repeats (just wanted to have entire code structure up to maybe answer some questions ahead of time).
/* Pack bits into containers to send them as 32-bit (4 bytes) items */
int finalBitPackage_1 = 0;
int finalBitPackage_2 = 0;
int finalBitPackage_3 = 0;
int finalBitPackage_4 = 0;
int finalBitPackage_5 = 0;
int finalBitPackage_6 = 0;
int finalBitPackage_7 = 0;
var bitContainer_1 = new BitArray(32, false);
var bitContainer_2 = new BitArray(32, false);
var bitContainer_3 = new BitArray(32, false);
var bitContainer_4 = new BitArray(32, false);
var bitContainer_5 = new BitArray(32, false);
var bitContainer_6 = new BitArray(32, false);
var bitContainer_7 = new BitArray(32, false);
string hexValue = String.Empty;
...
*assign 32 bits (from bools) to every bitContainer[] here*
...
/* Using this single 1-D array for all assignments works because as soon as we convert arrays,
we store the result; this way we never overwrite ourselves */
int[] data = new int[1];
/* Copy containers to a 1-dimensional array, then into an Int for transmission */
bitContainer_1.CopyTo(data, 0);
hexValue = data[0].ToString("X");
finalBitPackage_1 = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
bitContainer_2.CopyTo(data, 0);
hexValue = data[0].ToString("X");
finalBitPackage_2 = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
bitContainer_3.CopyTo(data, 0);
hexValue = data[0].ToString("X");
finalBitPackage_3 = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
bitContainer_4.CopyTo(data, 0);
hexValue = data[0].ToString("X");
finalBitPackage_4 = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
bitContainer_5.CopyTo(data, 0);
hexValue = data[0].ToString("X");
finalBitPackage_5 = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
bitContainer_6.CopyTo(data, 0);
hexValue = data[0].ToString("X");
finalBitPackage_6 = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
bitContainer_7.CopyTo(data, 0);
hexValue = data[0].ToString("X");
finalBitPackage_7 = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
From what I've learned so far, if a binary value is being converted to Int32, the first digit tells if it will be -/+, where 1 indicates (-) and 0 indicates (+); however, in my bitArrays that start with a 0, they show up as a negative number when I do the CopyTo(int[]) transaction, and the bitArrays that start with a 1 show up as a positive when they are copied.
In addition, there is the problem of converting them from their Int32 values into Hex values. Any values that come out of the array conversion as negative don't get the 8 F's added to the front as when checked by http://www.binaryhexconverter.com/, so I wasn't sure the difference in that since my Hex knowledge is limited and I didn't want to lose meaningful data when I transmit the data to another system (over TCP/IP if it matters to anyone). I'll post the values I'm getting out of everything below to help clear it up some.
Variable Binary Int32[] My Hex
bitContainer_1 "01010101010101010101010101010101" "-1431655766" AAAAAAAA
bitContainer_2 "10101010101010101010101010101010" "1431655765" 55555555
bitContainer_3 "00110011001100110011001100110011" "-858993460" CCCCCCCC
bitContainer_4 "11001100110011001100110011001100" "858993459" 33333333
bitContainer_5 "11100011100011100011100011100011" "-954437177" C71C71C7
bitContainer_6 "00011100011100011100011100011100" "954437176" 38E38E38
bitContainer_7 "11110000111100001111000011110000" "252645135" F0F0F0F
Online Hex Values:
FFFFFFFFAAAAAAAA
555555555
FFFFFFFFCCCCCCCC
33333333
FFFFFFFFC71C71C7
38E38E38
F0F0F0F
If every integer sign value is reversed place a -1*theIntegerValue to un-reverse it. It could also have something to do with when you're calling toStirng("X"), maybe use a blank string?
i have a string hex value, and i need to express it in 2's complement.
string hx = "FF00";
what i did is, converting it to binary:
string h = Convert.ToString(Convert.ToInt32(hx, 16), 2 );
then inverting it, but i couldn't use the NOT operator.
is there any short way to invert the bits and then adding 1 (2's complement operation)?
The answer might depend on whether or not the bit width of the value is important to you.
The short answer is:
string hx = "FF00";
uint intVal = Convert.ToUInt32(hx, 16); // intVal == 65280
uint twosComp = ~v + 1; // twosComp == 4294902016
string h = string.Format("{0:X}", twosComp); // h == "FFFF0100"
The value of h is then "FFFF0100" which is the 32-bit 2's complement of hx. If you were expecting '100' then you need to use 16-bit calculations:
string hx = "FF00";
ushort intVal = Convert.ToUInt16(hx, 16); // intVal = 65280
ushort twosComp = (ushort)(~v + 1); // twosComp = 256
string h = string.Format("{0:X}", twosComp); // h = "100"
Bear in mind that uint is an alias for UInt32 and ushort aliases the UInt16 type. For clarity in this type of operation you'd probably be better off using the explicit names.
Two complment is really simple:
int value = 100;
value = ~value // NOT
value = value + 1;
//Now value is -100
Remember that a two complement system requires inverting and adding plus 1.
In hex:
int value = 0x45;
value = ~value // NOT
value = value + 1;
I need to write a function which receives one parametrer of type int (decimal), and returns string containing the int value in hex, but in format 0xyy.
More than that I want the answer to be in a fixed format of 4 Bytes
For example:
int b = 358;
string ans = function(b);
In this case ans = "0x00 0x00 0x01 0x66"
int a = 3567846;
string ans = function(a);
In this case ans = "0x00 0x36 0x70 0xE6"
This should match your examples:
static string Int32ToBigEndianHexByteString(Int32 i)
{
byte[] bytes = BitConverter.GetBytes(i);
string format = BitConverter.IsLittleEndian
? "0x{3:X2} 0x{2:X2} 0x{1:X2} 0x{0:X2}"
: "0x{0:X2} 0x{1:X2} 0x{2:X2} 0x{3:X2}";
return String.Format(format, bytes[0], bytes[1], bytes[2], bytes[3]);
}
I think the format you want is on similar lines
int ahex = 3567846;
byte[] inthex = BitConverter.GetBytes(ahex);
Console.WriteLine("0x"+ BitConverter.ToString(inthex).Replace("-"," 0x"));
I have a byte array of size 4
byte[] source = new byte[4];
Now I wanted to convert this source into a 4-byte float value...
Can anyone tell me how to do this...
Try
float myFloat = System.BitConverter.ToSingle(mybyteArray, startIndex);