Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
In julia I am able to read the first 4 bytes from the file using this code. (It is the length of the message to read)
# Read the length in first 4 bytes
msglen = read(R.buffer, UInt32)
# Then read up to that length
bytes = read(R.buffer, msglen)
But when I try to read the same file in Rust the length value comes up way too big:
let mut f = std::fs::File::open("../20181002.bytes").unwrap();
let mut buf = Vec::new();
f.read_to_end(&mut buf).expect("file reading failed");
let mut dst = [0u8; 4];
let mut read_index = 0usize;
// select first 4 bytes of buf and clone into dst
dst.clone_from_slice(&buf[read_index..(read_index+4)]);
println!("Dst: {:?}", &buf[read_index..(read_index+4)]);
let length = u32::from_le_bytes(dst);
println!("Len: {}", length);
Dst: [31, 139, 8, 0]
Len: 559903
I think the first 4 bytes should be 1f8b 0800 0000 0000
If its of help, here is how its written in C#:
public static void Write(Stream stream, byte[] bytes)
{
var lengthBuffer = BitConverter.GetBytes(bytes.Length);
// Write object length.
stream.Write(lengthBuffer, offset: 0, count: 4);
// Write object.
stream.Write(bytes, offset: 0, count: bytes.Length);
}
1f8b is the magic number for gzip encoded files. Sorry to waste your time - leaving the code up in case it interests anyone.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am trying to round a number and the expected output isn't correct. Here's what I have tried:
var percent = Math.Round(1.13451, 0);
That above return's 1, but I want it to return 1.13 if the 3rd number is less than 5. If it's >= 5 (the third number) I want to get something like 1.135. I am sure it's something simple I am missing, but not sure.
It appears you are causing confusion because you're using the term "rounding" to describe an operation that is not actually rounding.
I've read your description again, and I can see that you're trying to truncate your values into the highest discrete increment of 0.005 that does not exceed the value.
You can do this as follows:
var percent = Math.Floor(200.0 * x) / 200.0;
Or, if you want it to be more obvious what's happening, this is essentially the same thing:
var increment = 0.005
var percent = Math.Floor(x / increment) * increment;
you have to write it with the amount of decimals you want. var percent = Math.Round(1.13451, 2);
Updated: I think this is the easiest way to do it.
static void Main(string[] args)
{
var percent = 1.13551;
char[] percent1 = percent.ToString().ToCharArray();
if (percent1[4] <= 5)
{
percent = Math.Round(percent, 3);
}
else
{
percent = Math.Round(percent, 2);
}
Console.WriteLine(percent);
Console.Read();
}
Use:
var percent = Math.Round(1.13451, 2);
Inside an if statement
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 3 years ago.
Improve this question
Currently I need to calculate 2^N, however N can be as large as 1929238932899 and I'm stuck using a long data type which can't hold a number that large.
I've currently tried converting to 'BigInt' however I'm still stuck with the long data type restriction from what I've seen as well.
I have a function which calculates the power. However, with the long data type, it just returns 0 when the number gets too big. Note that this is just a generic recursive power function.
For example, with 2^6 its meant to return 64 and with 2^47 to return 140737488355328. However, when it becomes 2^8489289, it just returns 0.
To represent 2^N in binary form, you need N+1 bits (binary digits), that is
(1 929 439 432 949 324 + 1) / 8 = 241 179 929 118 665.6 bytes ~ 219 PiB for a single number, if you really want to work with it.
Or you can just write down 2^N in binary form: 1 followed by N zeroes.
Since 2^N is an integer, you can represented it using Integer factorization.
You can put that in a class like this:
class FactorizedInteger {
private Dictionary<long, long> _factors = new Dictionary<long, long>();
public FactorizedInteger(long radix, long exponent) {
_factors[radix] = exponent;
}
public void Add(FactorizedInteger other) {
foreach(var factor in other._factors) {
if (_factors.ContainsKey(factor.Key)) {
_factors[factor.Key] += factor.Value;
} else {
_factors[factor.Key] = factor.Value;
}
}
}
public override string ToString() {
return "(" + String.Join(" + ", _factors.Select(p => $"{p.Key}^{p.Value}")) + ")";
}
}
As you can see, you can even add some mathematical operations without exhausting the memory of the computer. I've included Add as an example.
To use it:
var e1 = new FactorizedInteger(2, 1929238932899);
var e2 = new FactorizedInteger(2, 64);
Console.WriteLine(e1);
e1.Add(e2);
Console.WriteLine(e1);
Output:
(2^1929238932899)
(2^1929238932963)
This example needs to be made much smarter to be really usefull, but it is a possible representation of such large numbers.
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 4 years ago.
Improve this question
Basically, why does this work?
System.IO.Stream stream = new MemoryStream();
int a = 4;
byte[] barray = new byte[a];
stream.Write(barray, 0, Marshal.SizeOf(a));
When this doesn't:
System.IO.Stream stream = new MemoryStream();
int a = 3;
byte[] barray = new byte[a];
stream.Write(barray, 0, Marshal.SizeOf(a));
This is the error I get:
The offset and length were greater than allowed for the matrix, or the number is greater than the number of elements from the index to the end of the source collection.
When using Marshel.SizeOf(a) you ask the size of the object in memory. Since a is an int the size is always 4.
When you say byte[] barray = new byte[a]; you say:
Create an array called barray of type byte with length a. Thus in the first code block you create an array of length 4 and in the second one you create an array of length 3. Both array's contain only zero's.
Then you say: write the (empty) array to the stream, starting at position 0 and with length 4 (Marshel.SizeOf(a) is always 4 because a is an int).
The first example array has a length of 4 and thus works. The second example only contains 3 bytes and thus the length is not correct and you get an error.
If you wish to save the int to the stream as bytes explicitly you could call BitConverter:
System.IO.Stream stream = new MemoryStream();
int a = 4;
byte[] barray = System.BitConverter.GetBytes(a);
stream.Write(barray, 0, Marshal.SizeOf(a));
Now you say: create an array called barray that is filled with the binary representation of integer variable a.
And then write that filled array to the stream.
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
I have a table that stores the amount of RAM a server has in a biginit column with values such as 2470208.
But how I can apply a data annotation or other validations to show only 2 instead of s470208. ?
I mean to always divide by 1 million and get the number on the left side of the digit ?
1) Use this for automatic thousands-unit:
string GetByteString(long n) {
int k=0;
string u=" kMGTEP";
while(n>1024) {
n>>=10;
k++;
}
return n.ToString() + u[k];
}
Call:
string s= GetByteString(1234567890123);
Debug.WriteLine(s);
2) But if you simply always want MB just shift by 20:
long n = 123456789;
string MB = (n>>20).ToString();
But this will show 0 if n goes below 1MB.
Reason:
1 kB = 2^10 = 1<<10 = 1024;
1 MB = 2^20 = 1<<20 = 1024*1024 = 1048576;
1 GB = 2^30 = 1<<30 = 1024*1024*1024 = 1073741824;
You tagged C# but mentioned a bigint column so it isn't clear whether you're looking for a database or C# solution. The following C# method will take the number of bytes as an integer and return a formatted string...
public string FormattedBytes(long bytes)
{
string units = " kMGT";
double logBase = Math.Log((double)bytes, 1024.0);
double floorBase = Math.Floor(logBase);
return String.Format("{0:N2}{1}b",
Math.Pow(1024.0, logBase - floorBase),
units.Substring((int)floorBase, 1));
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How to append string and byte array?
String array="$MT!BOOTLOADER";
Byte[] hexdecimal={0x01,0x05,0x0036};
You probably want to do something low level, so in the end you won't need a string but a byte[], so:
string array="$MT!BOOTLOADER";
byte[] hexdecimal={0x01,0x05,0x36};
byte[] bytesOrig = Encoding.ASCII.GetBytes(array);
byte[] bytesFinal = bytesOrig;
Array.Resize(ref bytesFinal, bytesFinal.Length + hexdecimal.Length);
Array.Copy(hexdecimal, 0, bytesFinal, bytesOrig.Length, hexdecimal.Length);
// bytesFinal contains all the bytes
I'm using Encoding.ASCII because your signature is ASCII (and normally signatures are ASCII)
equivalent code, but little different (we preallocate the array with the right size, by doing two calls to Encoding.ASCII methods)
string array="$MT!BOOTLOADER";
byte[] hexdecimal={0x01,0x05,0x36};
int count = Encoding.ASCII.GetByteCount(array);
byte[] bytes = new byte[count + hexdecimal.Length];
Encoding.ASCII.GetBytes(array, 0, array.Length, bytes, 0);
Array.Copy(hexdecimal, 0, bytes, count, hexdecimal.Length);
// bytes contains all the bytes
Use this function for converting string to byte and byte to string.
static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
static string GetString(byte[] bytes)
{
char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
return new string(chars);
}