Is there way to convert float from 32bit integer? [closed] - c#

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
using c#
the float value i need to read
= 24.500000
when i try to read i get this result
= 1103364096
what conversion should i do to get the real value? i need help on this.
my failed attempts:
int data_1 = 1103364096;
UInt16 value = (UInt16)x;
ushort data_2= (ushort)(1103364096 & ((1 << 16) - 1));
int r = 1103364096;
short trimmed = unchecked((short)r);
these don't work!

As suggested by Jeremy, you need to use BitConverter.
We'll first get the byte representation of the integer i, then interpret those bytes as a float:
int i = 1103364096;
byte[] b = BitConverter.GetBytes(i);
float f = BitConverter.ToSingle(b, 0);
Console.WriteLine(f); // outputs 24.5
Try it online

Use Convert.ToFloat(x) to convert (from anything) to a float.
Use Convert.ToInt32(x) to convert (from anything) to an Int32.

Related

Equivalent of a C# byte[] in php? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
What is the equivalent of c#'s
byte[] buffer = File.ReadAllBytes(openFileDialog1.FileName);
in php?
Should I use file_read_contents(file) and then unpack the string into byte array?
I have zero experience in C# but I think what you're looking for is something like this
<?php
$file = fopen("file.txt","r");
while (! feof ($file))
echo fgetc($file);
fclose($file);
Your answer isn't very clear, I think you mean reading file as an array of bytes.
You can use unpack() function for this purpose:
$filename = "myFile.txt";
$handle = fopen($filename, "rb");
$fsize = filesize($filename);
$contents = fread($handle, $fsize);
$byteArray = unpack("N*",$contents);
print_r($byteArray);
for($n = 0; $n < 16; $n++)
{
echo $byteArray [$n].'<br/>';
}
otherwise you can get at the individual bytes similar to how you would in C:
$data = file_get_contents("myFile.txt");
for($i = 0; $i < strlen($data); ++$i) {
$char = $data[$i];
echo "Byte $i: $char\n";
}

How to Convert C++ sscanf_s() function to C# [closed]

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 6 years ago.
Improve this question
I want to convert following C++ code to C#, but I do not understand what the sscanf_s function does in this example or what its C# equivalent is.
int i, Len, iHex;
UCHAR Buf[20];
CString sHex;
CString Key = "abc";
Len = Key.GetLength() >> 1;
for(i = 0; i < Len; i++) {
sHex = sDesKey.Mid(i * 2, 2);
sscanf_s(sHex, _T("%x"), &iHex);
Buf[i] = ~iHex;
}
If I understand the function of sscanf_s correctly from Martin Bonner's explanation, you are looking for how to convert a string that represents hexadecimal digits into an int. You can do so with the following:
iHex = Convert.ToInt32(sHex, 16);
This being said, whether or not you want to actually use int for your conversion result depends on how you are implementing the rest of that function. (Not all ints are created equal across languages.)

Fastest way to read binary representation of data [closed]

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 6 years ago.
Improve this question
I am trying to read a file (>150 mb) and I need to read the binary representation of that file.
The file type is a .MP4.
I am trying to use this:
string.Join("-", x.Select(byt => Convert.ToString(byt, 2).PadLeft(8, '0')));
but the problems are:
1) It is too slow
2) It uses a lot of RAMs memory
If I read the raw bytes with
File.ReadAllBytes(path);
How Can I do that without having to convert the file into a string (method below)?
When working with big files like in your case, it would be better to just view a small part of the file (It's not like you can show the entire file at once anyhow).
Some Streams (like the FileStream) have the ability to Seek a certain position, which you can use to set your starting position.
if(position > _stream.Length)
throw new IndexOutOfRangeException();
if (position + length > _stream.Length)
length = (int) (_stream.Length - position);
_stream.Seek(position, SeekOrigin.Begin);
_stream.Read(buffer, 0, length);
The conversion to binary isn't that hard eiter, depending on the bit order you want, you'll probably have to reverse this (this is highest bit left 1 = 00000001). To gain some performance when building the string, use a StringBuilder instead of just concating strings with += or +.
public string ToBinary(byte value)
{
string result = "";
for (int i = 0; i < 8; i++)
{
result = value%2 + result;
value /= 2;
}
return result;
}
private string ToBinary(byte[] values)
{
StringBuilder builder = new StringBuilder();
int column = 0;
foreach (byte value in values)
{
builder.Append(ToBinary(value) + " ");
column++;
if (column == 8)
{
builder.AppendLine();
column = 0;
}
}
return builder.ToString();
}
Can can then eiter use it in a console application
https://dotnetfiddle.net/GVLm27
or put those two together with a TextBox and a ScrollBar and you have a good starting point:
ong position = (long) scrollBar1.Value;
byte[] data = new byte[128];
_file.GetSection(data, position, data.Length);
textBox1.Text = ToBinary(data);
After all those comments on your question I hope the original title is still what you are after
C# Fastest way to read binary representation of data

Converting a String to hex and calculate binary result in python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I got stuck with my code, tried anything on this side and many other things Google showed.
To the problem:
I try to convert some code-snips from C# to phyton, but on this special point i got stuck.
public static long decode(string data, int size, int offset = 0)
{
long value = 0;
for (int i = 0; i < size; ++i) {
value <<= 6;
value |= (long)data[offset + i] - 0x30;
}
return value;
}
The String Data could be something like 1Dh. Based on this I convert each char to the hex-equivalent: 0x31, 0x44, 0x68 and subtract 0x30; so I get 0x1, 0x14, 0x38;
In the next step I have to convert to the binary equivalent 000001, 010100, 111000 and merge this to
000001010100111000. From this I want to get the integer meaning, in this case 5432.
Is there a possibility to do this in a smart and easy way in python?
It's actually pretty easy, and the translation is pretty straight forward. You can continue to use your bit shifting. The only change is the syntax of for-loop and using ord() to get the integer value from a character.
def decode(data, size, offset=0):
value = 0
for ch in data[offset:size]:
value <<= 6
value |= ord(ch) - 0x30
return value
Running this in the interpreter, I get 5432:
>>> decode("1Dh", 3)
5432

How do display the Integer value of an IPAddress [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 14 years ago.
Improve this question
I was looking at the System.Net Namespace and it has an IPAddress instance you can use. This has a Parse method which you can use to parse a string into an IPInstance then use the Address property to give you the long value.
However...
The number returned is NOT the true conversion.
e.g. For IP 58.0.0.0 , the System.Net namespace gives me a value of 58...
When in fact, the integer value should be 973078528
Can someone please show me the correct code do convert this?
The formula should be.. (for ip 192.1.20.10).
192 * (256*256*256) + 1 * (256*256) + 20 * (256) + 10
The reason this formula is correct is that the number it returns you can use in a >= and <= query to determine an IP address that falls within a range.
The Address Property (of the IPAddress instance) does not calculate/return this. A bonus point for anyone that knows why the address property does not return what I think is the correct answer...
Other examples from other links did not work either.
Please see How to convert an IPv4 address into a integer in C#?
What you are seeing appears to be an endian problem.
As a generic function, if your IP address is A.B.C.D then the value you're after is:
A << 24 + (= A * 16777216)
B << 16 + (= B * 65536)
C << 8 + (= C * 256)
D
On little endian machines when the four-byte array ABCD is cast into an integer it comes out with A as the least significant byte instead of the most significant.
I don't write vb.net code, but it should be pretty trivial to knock out a function that'll do this.
You'll need to ensure that A - D are all in the 0 .. 255 range first, though!
How to convert an IPv4 address into a integer in C#?
example code is listed in the picked answer
e; f, b
This might work, will try it and see.
public double IPAddressToNumber(string IPaddress)
{
int i;
string [] arrDec;
double num = 0;
if (IPaddress == "")
{
return 0;
}
else
{
arrDec = IPaddress.Split('.');
for(i = arrDec.Length - 1; i >= 0 ; i = i -1)
{
num += ((int.Parse(arrDec[i])%256) * Math.Pow(256 ,(3 - i )));
}
return num;
}
}

Categories