C# How to extract bytes from double - c#

How can I extract bytes from double type. I know it has 8 bytes, just like long. How can I create a long variable that has the same bytes as the double has.
double a = 1.5;
long b = (long)a; // <- this returns 1
// i want to get this: 0 01111111111 1000000000000000000000000000000000000000000000000000
//which is 4609434218613702656 as long (I guess :) )
How can I do this quickly, please?

You can get it like this
double a = 1.5;
long l = BitConverter.ToInt64(BitConverter.GetBytes(a), 0);
It will be 4609434218613702656
As #harold suggested
var l2 = BitConverter.DoubleToInt64Bits(a);
is possible too

Related

Cannot calculate Long Data type in C#

I do not know why am I getting output as 0. Please help me to figure out my mistake in correcting the calculation for the long data type in C#. I have almost all variables in long to make it easier, but even then, the code does not work as expected.
long data_user;
long GB;
long MB;
long kB;
long bits;
long bits_rem;
double giga_C;
double mega_c;
double kilo_C;
double byte_C;
double sub_tot;
Console.Write("\nEnter the number of bytes used: ");
data_used = Console.Read();
//Divide data into each units.
GB = data_user / 1073741824;
giga_C = Convert.ToDouble(15.00 * GB);
MB = bits_rem / 1045214;
mega_C = (6.05 * MB);
kB = bits_rem / 10002;
kilo_C = (3.50 * kB);
bits = bits_rem / 0.1;
bits_C = (0.01 * bits);
sub_tot = (giga_C + mega_C + kilo_C + byte_C);
Console.Read reads the next character from the Console, so that you always get smaller number divided by big one (which is zero in integer arithmetic). For example, you write 1234, but Console.Read returns 49 because Unicode point for '1' is 49. Then you try to divide 49 by 1073741824 and obviously get 0.
You need to read your value as following Convert.ToInt64(Console.ReadLine())

how to round up a double value to nearest integer in c#

I am developing a windows forms application.I need to do some conversions and round up the values.I need to round up the double value to nearest integer.For example 1.4 should be 1 and 1.6 should be 2 after applying round up.Please refer my code below.
double d = 51386933935386.5;
uint x = (uint)Math.Round(d, 0, MidpointRounding.AwayFromZero);
After round up I need the value value = 51386933935386.But I am getting some different value.
The max value of UInt is 4,294,967,295.
You need to keep it a double or a long
EDIT: Or ulong if you want to keep it unsigned
51386933935386 is longer than uint max value. Use next:
double d = 51386933935386.5;
long x = (long)Math.Round(d, 0, MidpointRounding.AwayFromZero);
Why not use `Math.Floor(d);' ?
double d = 51386933935386.5;
var result = Math.Floor(d);
// result = 51386933935386
It returns the number you need.
Update
Thanks to #HimBromBeere to point it out you can accomplish your task using the code below.
Use this code
double d = 51386933935386.5;
var x = Math.Round(d, 0, MidpointRounding.AwayFromZero);
var result = Convert.ToInt64(x);

Converting non digit text to double and then back to string

I have a unique situation where I have to write code on top of an already establish platform so I am trying to figure out a hack to make something work.
The problem I have is I have a user defined string. Basically naming a signal. I need to get this into another program but the only method available is within a double value. Below is what I have tried but not been able to get it to work. I tried converting the string to byte array and then creating a new string by looping the bytes. Then I convert this string to a Double. Then use BitCoverter to get it back to byte array and then try to get the string.
Not sure if this can even be achieve. Any ideas?
string signal = "R3MEXA";
string newId = "1";
byte[] asciiBytes = System.Text.Encoding.ASCII.GetBytes(signal);
foreach (byte b in asciiBytes)
newId += b.ToString();
double signalInt = Double.Parse(newId);
byte[] bytes = BitConverter.GetBytes(signalInt);
string result = System.Text.Encoding.ASCII.GetString(bytes);
Asuming your string consists of ASCII characters (7Bit):
Convert your string into a bit-Array, seven bits per character.
Convert this bit-array into a string of digits, using 3 bits for each digit. (there are digits 0..7)
Convert this string of digits to a double number.
You initially set newId to "1", which means when you're doing later conversion, you're not going to get the right output unless to account for the "1" again.
It doesn't work, because if you convert it back you don't know the length of a byte.
So I made every byte to a length of 3.
string signal = "R3MEXA";
string newId = "1";
byte[] asciiBytes = System.Text.Encoding.ASCII.GetBytes(signal);
foreach (byte b in asciiBytes)
newId += b.ToString().PadLeft(3,'0'); //Add Zero, if the byte has less than 3 digits
double signalInt = Double.Parse(newId);
//Convert it back
List<byte> bytes = new List<byte>(); //Create a list, we don't know how many bytes will come (Or you calc it: maximum is _signal / 3)
//string _signal = signalInt.ToString("F0"); //Maybe you know a better way to get the double to string without scientific
//This is my workaround to get the integer part from the double:
//It's not perfect, but I don't know another way at the moment without losing information
string _signal = "";
while (signalInt > 1)
{
int _int = (int)(signalInt % 10);
_signal += (_int).ToString();
signalInt /= 10;
}
_signal = String.Join("",_signal.Reverse());
for (int i = 1; i < _signal.Length; i+=3)
{
byte b = Convert.ToByte(_signal.Substring(i, 3)); //Make 3 digits to one byte
if(b!=0) //With the ToString("F0") it is possible that empty bytes are at the end
bytes.Add(b);
}
string result = System.Text.Encoding.ASCII.GetString(bytes.ToArray()); //Yeah "R3MEX" The "A" is lost, because double can't hold that much.
What can improved?
Not every PadLeft is necessary. Work from back to front and if the third digit of a byte is greater than 2, you know, that the byte has only two digits. (Sorry for my english, I write an example).
Example
194 | 68 | 75 | 13
194687513
Reverse:
315786491
31 //5 is too big 13
57 //8 is too big 75
86 //4 is too big 68
491 //1 is ok 194

C# double to integer

Lets say I have the double 42.433243 and I would like to convert it to the integer 42433243.
What is the code for doing that when the decimal length is random?
Further examples:
45.25 => 4525
125.152254 => 125152254
etc...
You can multiply the value by 10 as long as there are any fraction part:
Decimal m = 42.433243m;
while (m % 1 != 0) m *= 10;
int i = (int)m;
Quick and dirty:
double x = 42.25;
int big = int.Parse(x.ToString().Replace(".",""));
This doesn't work if the number is too big (e.g. overflow, bigger than 2^32 for int, or you could replace int with double on line 2 and get it a lot larger).
Let me know if you have other considerations.
Perhaps something like this would work.
while ((double_num - Math.floor(double_num)) != 0.0) double_num *= 10;
int num = (int) double_num;
int result = Convert.ToInt32(Regex.Match(digits.Replace(".","").Replace(",",""), #"^\d+$").Value);
A more direct way to do this would be to convert the number to a decimal and examine the bits.
The first 96 least-significant bits represents the mantissa while the 32 most-significant bits represents the exponent. So the actual value that you would be interested in is the 32 least significant bits. The Decimal.GetBits() method returns the bits as an array ints so all you need to do is grab the first int in the array. As long as the numbers don't exceed int.MaxValue, you're golden.
var number = 42.433243;
var asDecimal = (Decimal)number;
var bits = Decimal.GetBits(asDecimal);
var digits = bits[0]; // 42433243

How to get integer quotient when divide two values in c#?

I want get integer quotient when I divide two values. Per example
X=3
Y=2
Q=X/Y = 1.5 // I want get 1 from results
X=7
Y=2
Q=X/Y=3.5 //I want get only 3 from results
Integer math is going to do this for you.
int x = 3 / 2; // x will be 1
int y = 7 / 2; // y will be 3
int z = 7 % 2; // z will be 1
If you were using decimal or floating-point values in your equations, that would be different. The simplest answer is to cast the result to an int, but there are static Math functions you could also use.
double a = 11d;
double b = 2d;
int c = (int)(a / b); // showing explicit cast, c will be 5
Try Math.Truncate. This should do it.
In VB.NET there is the integer division operator (\). It returns only the integer portion of the division. This comes all the way from the original Dartmouth BASIC so it exists in most forms of BASIC.
try Math.Floor()
There is another elegant way of getting quotient and remainder in .NET using Math.DivRem() method which takes 2 input parameter, 1 output parameter and returns integer.
using System;
For dividend: 7 and divisor: 2
To get only quotient(q)
int q = Math.DivRem(7, 2, _);
//requires C# >= 7.0 to use Discards( _ )
To get quotient(q) and remainder(r)
int q = Math.DivRem(7, 2, out int r);
Math.DivRem() has 2 overloads for 32-bit and 64-bit signed integers.
try using simple maths
int X = 10 ;
int Y = 3 ;
int Q = ( X - ( X % Y ) ) / Y ; // ( it will give you the correct answer )
It works by subtracting the remainder beforehand from the first number so that we don't get a remainder at all !

Categories

Resources