intBitsToFloat method in Java VS C#? - c#

I'm getting the wrong number when converting bits to float in C#.
Let's use this bit number= 1065324597
In Java, if I want to convert from bits to float I would use intBitsToFloat method
int intbits= 1065324597;
System.out.println(Float.intBitsToFloat(intbits));
Output: 0.9982942 which the correct output the I want to get in C#
However, in C# I used
int intbits= 1065324597;
Console.WriteLine((float)intbits);
Output: 1.065325E+09 Wrong!!
My question is how would you convert inbitsToFloat in C#?
My attempt:
I looked to the documentation here http://msdn.microsoft.com/en-us/library/aa987800(v=vs.80).aspx
but I still have the same trouble

Just casting is an entirely different operation. You need BitConverter.ToSingle(byte[], int) having converted the int to a byte array - and possibly reversed the order, based on the endianness you want. (EDIT: Probably no need for this, as the same endianness is used for both conversions; any unwanted endianness will just fix itself.) There's BitConverter.DoubleToInt64Bits for double, but no direct float equivalent.
Sample code:
int x = 1065324597;
byte[] bytes = BitConverter.GetBytes(x);
float f = BitConverter.ToSingle(bytes, 0);
Console.WriteLine(f);

i want to add on top of what jon skeet said, that also, for big float, if you don't want the "E+" output you should do:
intbits.ToString("N0");

Just try this...
var myBytes = BitConverter.GetBytes(1065324597);
var mySingle = BitConverter.ToSingle(myBytes,0);
The BitConverter.GetBytes converts your integer into a four byte array. Then BitConverter.ToSingle converts your array into a float(single).

Related

BigInteger.Parse() trouble reading in large numbers

Presently I am attempting to do this challenge (http://cryptopals.com/sets/1/challenges/1) and I am having some trouble completing the task in C#. I can not seem to parse the number into a big integer.
So code looks like below:
string output = "";
BigInteger hexValue = BigInteger.Parse("49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6");
output = Convert.ToBase64String(hexValue.ToByteArray());
Console.WriteLine(hexValue);
Console.WriteLine(output);
Console.ReadKey();
return "";
And at present the problem I am getting is when I run the program it fails with the error
System.FormatException: 'The value could not be parsed.' and I am not entirely sure why.
So, what is the appropriate way to get a large integer from a string into a BigInt?
The initial problem
The BigInteger.Parse method expects the value to be decimal, not hex. You can "fix" that by passing in NumberStyles.HexNumber.
The bigger problem with using BigInteger for this
If you're just trying to convert a string of hex digits into bytes, I would avoid using BigInteger at all. For one thing, you could end up with problems if the original byte array started with zeroes, for example. The zeroes wouldn't be in the resulting byte array. (Sample input: "0001" - you want to get two bytes out, but you'll only get one, after persuading it to parse hex.)
Even if you don't lose any information, the byte[] you receive from BigInteger.ToByteArray() isn't what you were probably expecting. For example, consider this code, which just converts the data to byte[] and back to hex via BitConverter:
BigInteger bigInt = BigInteger.Parse("1234567890ABCDEF", NumberStyles.HexNumber);
byte[] bytes = bigInt.ToByteArray();
Console.WriteLine(BitConverter.ToString(bytes));
The output of that is "EF-CD-AB-90-78-56-34-12" - because BigInteger.ToByteArray returns the data in little-endian order:
The individual bytes in the array returned by this method appear in little-endian order. That is, the lower-order bytes of the value precede the higher-order bytes.
That's not what you want - because it means the last part of the original string is the first part of the byte array, etc.
Avoiding BigInteger altogether
Instead, parse the data directly to a byte array, as in this question, or this one, or various others. I won't reproduce the code here, but it's simple enough, with different options depending on whether you're trying to create simple source code or an efficient program.
General advice on conversions
In general it's a good idea to avoid intermediate representations of data unless you're absolutely convinced that you won't lose information in the process - as you would here. It's fine to convert the hex string to a byte array before converting the result to base64, because that's not a lossy transformation.
So your conversions are:
String (hex) to BigInteger: lossy (in the context of leading 0s being significant, as they are in this situation)
BigInteger to byte[]: not lossy
byte[] to String (base64): not lossy
I'm recommending:
String (hex) to byte[]: not lossy (assuming you have an even number of nybbles to convert, which is generally a reasonable assumption)
byte[] to String (base64): not lossy
Use NumberStyles.HexNumber:
BigInteger.Parse("49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6",
NumberStyles.HexNumber,
CultureInfo.InvariantCulture);
If your number is supposed to be always positive, add a leading zero to your string.
The problem is that the input is not decimal but hexadecimal, therefore you need to pass an additional parameter for parsing:
BigInteger number = BigInteger.Parse(
hexString,
NumberStyles.AllowHexSpecifier);

Are there compiling differences between Hexadecimal and Decimal numbers?

int foo = 510;
int bar = 0x0001FE;
Are there compiling differences between these two declarations?
For example, does your computer read these two values different?
No, but Hex is clerer to read as human if you look for bit / byte values.
Internally all is binary and the compiler does convert it to binary representation anyway.

Reading 4-byte IEEE float in .NET

I'm trying to read a binary file which contains numbers encoded in 4-byte IEEE float. I'm doing this using the .NET BinaryReader, but am unsure how to correctly read the data. I'm certainly sure that the ReadSingle() method is not giving me the value I'm looking for.
Does anyone know how to do this in .NET?
If the BitConverter.ToSingle method isn't working for you, you may need to look into
Array.Reverse to change the order of your bytes.
You really didn't provide any code in your question (which is strongly suggested),
but I'm guessing its like:
byte[] myData = new byte[4];
myBinReader.Read(myData, 0, 4); // Get 4-bytes from the stream.
Array.Reverse(myData); // Deal with Endian issue?
Single myvalue = BitConverter.ToSingle(myData, 4);
Use the BitConverter.ToSingle method
Loop through your input (or read your stream) and make use of BitConverter
float value = BitConverter.ToSingle( bytes, index );

Does Integer.valueOf() in java translate to int.Parse() in C#?

I am trying to learn java from a C# background! I have found some nuances during my journey like C# doesn't have an Integer as reference type it only has int as a primitive type; this lead me to a doubt if this translation would be correct!
String line ="Numeric string";//Java
string line = "Numeric string";//C#
int size;
size = Integer.valueOf(line, 16).intValue(); //In Java
size = int.Parse(line,System.Globalization.NumberStyles.Integer);//In C#
No, that's not quite a valid translation - because the 16 in the Java code means it should be parsed as an integer. The Java code is closer to:
int size = Convert.ToInt32(line, 16);
That overload of Convert.ToInt32 allows you to specify the base.
Alternatively you could use:
int size = int.Parse("11", NumberStyles.AllowHexSpecifier);
I'm not keen on the name "allow hex specifier" as it suggests that a prefix of "0x" will be accepted... but in reality it means it's always interpreted as hex.
In java, this is better:
Integer.parseInt(line, 16);
it parse a string into int, while Integer.valueOf converts to Integer.

byte array to double conversion in c#

I have an array of three bytes, I want to convert array into double using c#. Kindly guide me.
Well, that depends on what you want the conversion to do.
You can convert 8 bytes (in the right format) into a double using BitConverter.ToDouble - but with only three bytes it's a bit odd - after all, a double has 64 bits of information, normally. How do those three bytes represent a number? What's the format, basically? When you've figured that out, the rest may well be easy.
Well a double is an array of 8 bytes, so with 3 bytes you won't have all the possible values.
To do what you want:
var myBytes[] = {0,0,0,0,0,1,1,2}; //assume you pad your array with enough zeros to make it 8 bytes.
var myDouble = BitConverter.ToDouble(myBytes,0);
Depends on what exactly is stored in the bytes, but you might be able to just pad the array with 5 bytes all containing 0 and then use BitConverter.ToDouble.

Categories

Resources