c# read serial in hex - c#

I am using the SDS011 laser dust sensor and want to read the data in a Windows forms Application.
I get Hex Data. Example: AA C0 D4 04 3A 0A A1 60 1D AB
now the fourth and the third pair represent the PM2.5 value, in this example: 04D4 -> 1236 -> 123,6 ug/m^3
Could you please help me write a code for reading in the hex data and calculating the PM2.5 value?
Thanks.

If the data is coming as a string then it's simple as:
string inputData = "AA C0 D4 04 3A 0A A1 60 1D AB";
var inputDataSplit = inputData.Split(' ');
// Concatenate the fourth and the third string, and convert it to integer with base 16 (hex)
int pmValue = Convert.ToInt32(inputDataSplit[3] + inputDataSplit[2], 16);
// 1236
Console.Write(pmValue);

Related

Use public Rsa key in C# [duplicate]

I'm currently trying to create an RSACryptoServiceProvider object solely from a decoded PEM file. After several days of searching, I did manage to wrangle a working solution but it's not one that would be production ready.
In a nutshell, in order to create an RSACryptoServiceProvider object from the bytes that make up the public key in a PEM file, I must create the object specifying the keysize (currently 2048 using SHA256, specifically) and then importing a RSAParameters object with the Exponent and Modulus set. I'm doing this as so;
byte[] publicKeyBytes = Convert.FromBase64String(deserializedPublicKey.Replace("-----BEGIN PUBLIC KEY-----", "")
.Replace("-----END PUBLIC KEY-----", ""));
// extract the modulus and exponent based on the key data
byte[] exponentData = new byte[3];
byte[] modulusData = new byte[256];
Array.Copy(publicKeyBytes, publicKeyBytes.Length - exponentData.Length, exponentData, 0, exponentData.Length);
Array.Copy(publicKeyBytes, 9, modulusData, 0, modulusData.Length);
// import the public key data (base RSA - works)
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(dwKeySize: 2048);
RSAParameters rsaParam = rsa.ExportParameters(false);
rsaParam.Modulus = modulusData;
rsaParam.Exponent = exponentData;
rsa.ImportParameters(rsaParam);
While this works, it's not viable to assume that the deserializedPublicKey will be exactly 270 bytes and that the modulus I need is found at position 9 and always be 256 bytes in length.
How do I change this to correctly pick out the Modulus and Exponent byte given a set of public key bytes? I've tried to make sense of the ASN.1 standard but with little luck finding what I need from it - the standard(s) are somewhat byzantine.
Any help is appreciated.
You don't need to export existing parameters then re-import over top of them. That forces your machine to generate an RSA key then throw it away. So specifying a keysize to the constructor doesn't matter (if you don't use the key it won't generate one... usually).
The public key file is a DER encoded blob.
-----BEGIN PUBLIC KEY-----
MIGgMA0GCSqGSIb3DQEBAQUAA4GOADCBigKBggC8rLGlNJ17NaWArDs5mOsV6/kA
7LMpvx91cXoAshmcihjXkbWSt+xSvVry2w07Y18FlXU9/3unyYctv34yJt70SgfK
Vo0QF5ksK0G/5ew1cIJM8fSxWRn+1RP9pWIEryA0otCP8EwsyknRaPoD+i+jL8zT
SEwV8KLlRnx2/HYLVQkCAwEAAQ==
-----END PUBLIC KEY-----
If you take the contents inside the PEM armor, it's a Base64-encoded byte array.
30 81 A0 30 0D 06 09 2A 86 48 86 F7 0D 01 01 01
05 00 03 81 8E 00 30 81 8A 02 81 82 00 BC AC B1
A5 34 9D 7B 35 A5 80 AC 3B 39 98 EB 15 EB F9 00
EC B3 29 BF 1F 75 71 7A 00 B2 19 9C 8A 18 D7 91
B5 92 B7 EC 52 BD 5A F2 DB 0D 3B 63 5F 05 95 75
3D FF 7B A7 C9 87 2D BF 7E 32 26 DE F4 4A 07 CA
56 8D 10 17 99 2C 2B 41 BF E5 EC 35 70 82 4C F1
F4 B1 59 19 FE D5 13 FD A5 62 04 AF 20 34 A2 D0
8F F0 4C 2C CA 49 D1 68 FA 03 FA 2F A3 2F CC D3
48 4C 15 F0 A2 E5 46 7C 76 FC 76 0B 55 09 02 03
01 00 01
ITU-T X.690 defines how to read things encoded under Basic Encoding Rules (BER), Canonical Encoding Rules (CER, which I've never seen explicitly used), and Distinguished Encoding Rules (DER). For the most part CER restricts BER and DER restricts CER, making DER the easiest to read. (ITU-T X.680 describes Abstract Syntax Notation One (ASN.1), which is the grammar that DER is a binary encoding for)
We can do a bit of parsing now:
30
This identifies a SEQUENCE (0x10) with the CONSTRUCTED bit set (0x20), which means that it contains other DER/tagged values. (SEQUENCE is always CONSTRUCTED in DER)
81 A0
This next part is a length. Since it has the high bit set (> 0x7F) the first byte is a "length length" value. It indicates that the true length is encoded in the next 1 byte(s) (lengthLength & 0x7F). Therefore the contents of this SEQUENCE are 160 bytes total. (In this case, "the rest of the data", but the SEQUENCE could have been contained within something else). So let's read the contents:
30 0D
We see our CONSTRUCTED SEQUENCE again (0x30), with a length value of 0x0D, so we have a 13 byte payload.
06 09 2A 86 48 86 F7 0D 01 01 01 05 00
The 06 is OBJECT IDENTIFIER, with a 0x09 byte payload. OID has a slightly non-intuitive encoding, but this one is equivalent to the text representation 1.2.840.113549.1.1.1, which is id-rsaEncryption (http://www.oid-info.com/get/1.2.840.113549.1.1.1).
This still leaves us with two bytes (05 00) which we see is a NULL (with a 0 byte payload, because, well, it's NULL).
So so far we have
SEQUENCE
SEQUENCE
OID 1.2.840.113549.1.1.1
NULL
143 more bytes.
Continuing on:
03 81 8E 00
The 03 means BIT STRING. BIT STRING is encoded as [tag] [length] [number of unused bits]. The unused bits is essentially always zero. So this is a sequence of bits, 0x8E bytes long, and all of them are used.
Technically we should stop there, because CONSTRUCTED wasn't set. But since we happen to know the format of this structure, we treat the value as if the CONSTRUCTED bit was set anyways:
30 81 8A
Here's our friend CONSTRUCTED SEQUENCE again, 0x8A payload bytes, which conveniently corresponds to "everything that's left".
02 81 82
02 identifies an INTEGER, and this one has 0x82 payload bytes:
00 BC AC B1 A5 34 9D 7B 35 A5 80 AC 3B 39 98 EB
15 EB F9 00 EC B3 29 BF 1F 75 71 7A 00 B2 19 9C
8A 18 D7 91 B5 92 B7 EC 52 BD 5A F2 DB 0D 3B 63
5F 05 95 75 3D FF 7B A7 C9 87 2D BF 7E 32 26 DE
F4 4A 07 CA 56 8D 10 17 99 2C 2B 41 BF E5 EC 35
70 82 4C F1 F4 B1 59 19 FE D5 13 FD A5 62 04 AF
20 34 A2 D0 8F F0 4C 2C CA 49 D1 68 FA 03 FA 2F
A3 2F CC D3 48 4C 15 F0 A2 E5 46 7C 76 FC 76 0B
55 09
The leading 0x00 would be a violation of DER, except the next byte has the high bit set. This means that the 0x00 was there to keep the sign bit from being set, making this a positive number.
02 03 01 00 01
Another INTEGER, 3 bytes, value 01 00 01. And we're done.
SEQUENCE
SEQUENCE
OID 1.2.840.113549.1.1.1
NULL
BIT STRING
SEQUENCE
INTEGER 00 BC AC ... 0B 55 09
INTEGER 01 00 01
Harvesting https://www.rfc-editor.org/rfc/rfc5280 we see that this looks a lot like a SubjectPublicKeyInfo structure:
SubjectPublicKeyInfo ::= SEQUENCE {
algorithm AlgorithmIdentifier,
subjectPublicKey BIT STRING }
AlgorithmIdentifier ::= SEQUENCE {
algorithm OBJECT IDENTIFIER,
parameters ANY DEFINED BY algorithm OPTIONAL }
-- contains a value of the type
-- registered for use with the
-- algorithm object identifier value
Of course, it doesn't know what the RSA public key format is. But the oid-info site told us to check out RFC 2313, where we see
An RSA public key shall have ASN.1 type RSAPublicKey:
RSAPublicKey ::= SEQUENCE {
modulus INTEGER, -- n
publicExponent INTEGER -- e }
So that says that the first INTEGER we read is the Modulus value, and the second is (public)Exponent.
The DER encoding is big-endian, which is also the RSAParameters encoding, but for RSAParameters you need to remove leading 0x00 values from Modulus.
While that isn't as easy as giving you the code to do it, it should be fairly straightforward to write a parser for RSA keys given this information. I'd recommend that you write it as internal static RSAParameters ReadRsaPublicKey(...), and then you just need to do
RSAParameters rsaParameters = ReadRsaPublicKey(...);
using (RSA rsa = RSA.Create())
{
rsa.ImportParameters(rsaParameters);
// things you want to do with the key go here
}
After a lot of time, searching and bartonjs's outstanding response, the code to do this is actually straight forward in the end albeit a little unintuitive to anyone not familiar with the structure of a public key.
TL;DR Basically, if your public key is coming from a non-.NET source, this answer won't help as .NET doesn't provide a way to natively parse a correctly formed PEM. However, if the code that generated the PEM is .NET based, then this answer describes the creation of the public key-only PEM and how to load it back in.
A public key PEM can describe a variety of key types, not just RSA so rather than something like new RSACryptoServiceProvider(pemBytes), we have to parse the PEM based on its structure/syntax, ASN.1, and it then tells us if it's an RSA key (it could be a range of others). Knowing that;
const string rsaOid = "1.2.840.113549.1.1.1"; // found under System.Security.Cryptography.CngLightup.RsaOid but it's marked as private
Oid oid = new Oid(rsaOid);
AsnEncodedData keyValue = new AsnEncodedData(publicKeyBytes); // see question
AsnEncodedData keyParam = new AsnEncodedData(new byte[] { 05, 00 }); // ASN.1 code for NULL
PublicKey pubKeyRdr = new PublicKey(oid, keyParam, keyValue);
var rsaCryptoServiceProvider = (RSACryptoServiceProvider)pubKeyRdr.Key;
NOTE: The above code is not production ready! You'll need to put appropriate guards around the object creation (e.g. the public key might not be RSA), the cast to RSACryptoServiceProvider, etc. The code sample here is short to illustrate that it can be done reasonably cleanly.
How did I get this? Spelunking down through the Cryptographic namespace in ILSpy, I had noticed AsnEncodedData which rang a bell with bartonjs's description. Doing more research, I happened upon this post (look familiar?). This was trying to determine the key size specifically but it creates the necessary RSACryptoServiceProvider along the way.
I'm leaving bartonjs's answer as Accepted, and rightly so. The code above is the result of that research and I'm leaving it here so that others looking to do the same can do so cleanly without any array copying hacks like I had in my OP.
Also, for decoding and testing purposes, you can check if your public key is parsable using the ASN.1 decoder here.
UPDATE
It's on the .NET roadmap to make this easier with ASN.1 parsing for Core >2.1.0.
UPDATE 2
There is now a private implementation in Core .NET 2.1.1. MS is dogfooding until satisfied all is well and we'll (hopefully) see the public API in a subsequent version.
UPDATE 3
As I found out via a question here, the above info is incomplete. What's missing is that the public key being loaded with this solution is one that was generated programmatically from a loaded public+private key pair. Once an RSACryptoServiceProvider is created from a key pair (not just the public key), you can export just the public bytes and encode them as a public key PEM. Doing so will be compatible with the solution here. What's with this?
Load the public + private keypair into an RSACryptoServiceProvider and then export it like so;
var cert = new X509Certificate2(keypairBytes, password,
X509KeyStorageFlags.Exportable
| X509KeyStorageFlags.MachineKeySet);
var partialAsnBlockWithPublicKey = cert.GetPublicKey();
// export bytes to PEM format
var base64Encoded = Convert.ToBase64String(partialAsnBlockWithPublicKey, Base64FormattingOptions.InsertLineBreaks);
var pemHeader = "-----BEGIN PUBLIC KEY-----";
var pemFooter = "-----END PUBLIC KEY-----";
var pemFull = string.Format("{0}\r\n{1}\r\n{2}", pemHeader, base64Encoded, pemFooter);
If you create a PEM from this key, you'll be able to load it back in using the method described earlier. Why is this different? The call to cert.GetPublicKey() will actually return the ASN.1 block structure;
SEQUENCE(2 elem)
INTEGER (2048 bit)
INTEGER 65537
This is actually an incomplete DER blob but one which .NET can decode (full ASN.1 parsing and generation is not supported by .NET at time of writing - https://github.com/dotnet/designs/issues/11).
A correct DER (ASN.1) encoded public key bytes has the following structure;
SEQUENCE(2 elem)
SEQUENCE(2 elem)
OBJECT IDENTIFIER "1.2.840.113549.1.1.1" - rsaEncryption(PKCS #1)
NULL
BIT STRING(1 elem)
SEQUENCE(2 elem)
INTEGER (2048 bit)
INTEGER 65537
OK, so the above gets you a public key (kind of) that you can load. It's ugly and technically incomplete but does use .NET's own output from RSACryptoServiceProvider.GetPublicCert() method. The constructor can use those same bytes when loading just the public key later. Unfortunately, it's not a true, fully-formed PEM. We're still awaiting MS's ASN.1 parser in .NET Core 3.0>.
PEM files are just a serie of base64 encoded DER files and .net allow to import directly DER files, so you can do something like this (I assume you're using just the public key as you state you use it only):
byte[] certBytes = Convert.FromBase64String(deserializedPublicKey
.Replace("-----BEGIN PUBLIC KEY-----", "")
.Replace("-----END PUBLIC KEY-----", ""));
X509Certificate2 cert = new X509Certificate2(certBytes);
RSACryptoServiceProvider publicKeyProvider =
(RSACryptoServiceProvider)cert.PublicKey.Key;

c# convert bytes to double with a "higher" precision

I always convert bytes to double with System.BitConverter.ToDouble() like this:
double value = BitConverter.ToDouble(flt, 0);//flt is an array of bytes.
But when I try to convert "8A 7F DA 0C 41 6D A6 40"(Little Endian),it become 2870.62705118949.
Indeed, 2870.62705118949 is "8E 7F DA 0C 41 6D A6 40".
But what I want is 2870.6270511894881565.How can I get the accurate value using C#?
When working with exact string representation, use "R" formatting:
https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx
"R" or "r" Round-trip Result: A string that can round-trip to an
identical number.
In your case
Byte[] data = { 0x8A, 0x7F, 0xDA, 0x0C, 0x41, 0x6D, 0xA6, 0x40 };
Double value = BitConverter.ToDouble(data, 0);
Console.Write(value.ToString("R", CultureInfo.InvariantCulture)); // "R" formatting
And as you can see, the actual value is not 2870.62705118949 but 2870.6270511894882; just compare the values:
2870.6270511894882 Actual
2870.6270511894881565 You want to have
2870.62705118949 Proposed by changing 8A into 8E
and see that "8A 7F DA 0C 41 6D A6 40" is, in fact, a better choice (more accurate)

RSA modulus and exponent from public key

I basically have the same problem as in this question, but I'm having trouble filling in the apparently trivial parts left out from the accepted answer. I'm doing this in C# with Mono.
I have a CA root certificate, and from that I can get a byte[] holding a public key. I then get an untrusted certificate I need to verify. From what I understand, RSACryptoServiceProvider.VerifyData should do the trick, but first I need to set RSAParameters with the modulus and exponent from the public key.
(Edit: The following repeats some things already apparent from the question I linked to above.)
The piece of code that should do what I need and validate a server's certificate with a root certificate I trust is as follows:
RSACryptoServiceProvider publicKey = new RSACryptoServiceProvider();
RSAParameters publicKeyParams = new RSAParameters();
publicKeyParams.Modulus = GetPublicKeyModulus();
publicKeyParams.Exponent = GetPublicKeyExponent();
publicKey.ImportParameters(publicKeyParams);
return publicKey.VerifyData(SignedValue(), CryptoConfig.MapNameToOID("SHA1"), Signature());
My problem is the contents of the GetPublicKeyModulus() and GetPublicKeyExponent(). In the accepted answer they are left out as apparently trivial, with just a comment saying the modulus is the value of the first TLV in my public key, and the exponent is the second TLV in the public key. I don't fully understand what that means.
byte[] GetPublicKeyExponent()
{
// The value of the second TLV in your Public Key
}
byte[] GetPublicKeyModulus()
{
// The value of the first TLV in your Public Key
}
byte[] SignedValue()
{
// The first TLV in your Ceritificate
}
byte[] Signature()
{
// The value of the third TLV in your Certificate
}
My question is what do these "first TLV"/"second TLV" exactly mean and how do I get those values from the byte array I have?
From what I understand, TLV stands for type-length-value. So if I have it correct, first bits of the byte array containing the public key have information about how many bits the modulus data is. Using that information I'm supposed to copy that amount of bits from the public key into another array, and set RSAParameters.Modulus to that value. After the modulus in the public key comes the exponent, and I should do the same operation with that. But I can't find information about in how many bits and in what format is the "TL" part of a TLV in the public key data contained.
I found information elsewhere saying the modulus is the first 1024 bits in the public key, and the exponent is the remainder, but that gave me an error about size when copying data between the byte arrays.
At the moment my code that I've been forming based on the accepted answer in the question I linked looks basically like this:
using System;
using System.Net;
using System.Security.Cryptography.X509Certificates;
X509Certificate2 trustedRootCertificate = new X509Certificate2(X509Certificate2.CreateFromCertFile(filename));
ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate;
.
.
public bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
.
.
byte[] publicKeyBytes = trustedRootCertificate.GetPublicKey();
byte[] modulusData = // The value of the first TLV in the Public Key??
byte[] exponentData = // The value of the second TLV in the Public Key??
RSAParameters publicKeyParams = new RSAParameters();
publicKeyParams.Modulus = modulusData;
publicKeyParams.Exponent = exponentData;
RSACryptoServiceProvider publicKey = new RSACryptoServiceProvider();
publicKey.ImportParameters(publicKeyParams);
byte[] certificateData = certificate.GetRawCertData();
byte[] signedValue = // The first TLV in the certificate??
byte[] encryptedSignature = // The third TLV in the certificate??
return publicKey.VerifyData(certificateData, HashAlgorithm.Create("SHA1"), encryptedSignature);
}
Or should I be using certificateData (the return value of certificate.GetRawCertData()) in the VerifyData call?
Elsewhere I've found that the encrypted signature part is the last 256 bits in the certificateData, I'm not sure if that's the same as "the third TLV in the certificate". If not, I'd be doing
byte[] certificateData = certificate.GetRawCertData();
byte[] encryptedSignature = new byte[256];
System.Array.Copy(certificateData, certificateData.Length - 256, encryptedSignature, 0, 256);
and then using encryptedSignature as the last parameter in the VerifyData call.
Instead of all this TLV business I've also tried simply
RSACryptoServiceProvider publicKey = trustedRootCertificate.PublicKey.Key as RSACryptoServiceProvider;
as the person in the question I linked to above, but using this the VerifyData call then returned false when I thought it shouldn't. The certificate the application gets from the server has trustedRootCertificate as its root cert, I should be able to do this with that, correct? The root's public key should be able to verify the server's cert?
It's very much possible I just have the very basics of certificate verification wrong from the start. If that's not the case, then my question is how do I get these values
// The value of the second TLV in your Public Key
..
// The value of the first TLV in your Public Key
from the public key of the trusted root cert I have.
Edit: I've also verified that the root certificate loaded from the file and the certificate the app gets from the server are what they're supposed to be by printing out their information, so the problem is not at least in the certificates being wrong. I just don't know how to use them correctly.
Lets say that you encountered with BIT STRING type containing the following Length - Value::
03(T - BIT STRING)
82(Read next 2 Bytes for actual Length)
01 0F(Actual Length of whole BIT STRING)
---BIT STRING Value Starts Here---
00(First Byte Of BIT STRING specifies the number of bits left unused in the final byte of BIT STRING which in this case is 0)
30(T - SEQUENCE)
82(Read next 2 Bytes for actual Length)
01 0A(Actual Length of whole SEQUENCE)
---SEQUENCE Value Starts Here---
02(T - INTEGER)
82(Read next 2 Bytes for actual Length)
01 01(Actual Length of whole INTEGER)
(Value starts from here till "Actual Length of whole INTEGER above")
---INTEGER Value Starts Here---
---Exponent Starts Here---
00 A9 CA B2 A4 CC CD 20 AF 0A
7D 89 AC 87 75 F0 B4 4E F1 DF C1 0F BF 67 61 BD
A3 64 1C DA BB F9 CA 33 AB 84 30 89 58 7E 8C DB
6B DD 36 9E 0F BF D1 EC 78 F2 77 A6 7E 6F 3C BF
93 AF 0D BA 68 F4 6C 94 CA BD 52 2D AB 48 3D F5
B6 D5 5D 5F 1B 02 9F FA 2F 6B 1E A4 F7 A3 9A A6
1A C8 02 E1 7F 4C 52 E3 0E 60 EC 40 1C 7E B9 0D
DE 3F C7 B4 DF 87 BD 5F 7A 6A 31 2E 03 99 81 13
A8 47 20 CE 31 73 0D 57 2D CD 78 34 33 95 12 99
12 B9 DE 68 2F AA E6 E3 C2 8A 8C 2A C3 8B 21 87
66 BD 83 58 57 6F 75 BF 3C AA 26 87 5D CA 10 15
3C 9F 84 EA 54 C1 0A 6E C4 FE C5 4A DD B9 07 11
97 22 7C DB 3E 27 D1 1E 78 EC 9F 31 C9 F1 E6 22
19 DB C4 B3 47 43 9A 1A 5F A0 1E 90 E4 5E F5 EE
7C F1 7D AB 62 01 8F F5 4D 0B DE D0 22 56 A8 95
CD AE 88 76 AE EE BA 0D F3 E4 4D D9 A0 FB 68 A0
AE 14 3B B3 87 C1 BB
-----Exponent Ends Here----
---INTEGER Value Ends Here---
02(T - INTEGER)
03(Actual Length cuz 8th Bit Not Set here, so this byte shows the actual length)
---INTEGER Value Starts Here---
----Mod Starts Here---
01 00 01
---Mod Ends Here---
---INTEGER Value Ends Here---
---SEQUENCE Value Ends Here---
---BIT STRING Value Ends Here---
You might want to read ASN.1 Format
With RSACryptoServiceProvider:
X509Certificate2 certificate = Certificate.CreateFromBase64String(stringCert);
RSACryptoServiceProvider key = certificate.PublicKey.Key as RSACryptoServiceProvider;
if(key != null)
{
RSAParameters parameters = key.ExportParameters(false);
byte[] expoenet = parameters.Exponent;
byte[] modulus = parameters.Modulus;
}
https://social.msdn.microsoft.com/Forums/vstudio/en-US/4282dda1-4803-435a-b63a-65e2d5ac9941/get-modulus-exponent-from-certificate-public-key?forum=netfxbcl

Odd decimal type behavior for ToString(IFormatProvider)

var numberFormat = new NumberFormatInfo();
numberFormat.NumberDecimalSeparator = ".";
numberFormat.NumberDecimalDigits = 2;
decimal a = 10.00M;
decimal b = 10M;
Console.WriteLine(a.ToString(numberFormat));
Console.WriteLine(b.ToString(numberFormat));
Console.WriteLine(a == b ? "True": "False");
In console:
10.00
10
True
Why is it different? More important, how do I call ToString() to ensure same output no matter how a variable is initialized?
The question of how to make it output consistently has been answered, but here is why they output differently in the first place:
A decimal value contains, internally, fields for a scale and a coefficient. In the case of 10M, the value encoded has a coefficient of 10 and a scale of 0:
10M = 10 * 10^0
In the case of 10.00M, the value encoded has a coefficient of 1000 and a scale of 2:
10.00M = 1000 * 10^(-2)
You can sort of see this by inspecting the values in-memory:
unsafe
{
fixed (decimal* array = new decimal[2])
{
array[0] = 10M;
array[1] = 10.00M;
byte* ptr = (byte*)array;
Console.Write("10M: ");
for (int i = 0; i < 16; i++)
Console.Write(ptr[i].ToString("X2") + " ");
Console.WriteLine("");
Console.Write("10.00M: ");
for (int i = 16; i < 32; i++)
Console.Write(ptr[i].ToString("X2") + " ");
}
}
Outputs
10M: 00 00 00 00 00 00 00 00 0A 00 00 00 00 00 00 00
10.00M: 00 00 02 00 00 00 00 00 E8 03 00 00 00 00 00 00
(0xA is 10 in hex, and 0x3E8 is 1000 in hex)
This behaviour is outlined in section 2.4.4.3 of the C# spec:
A real literal suffixed by M or m is of type decimal. For example, the literals 1m, 1.5m, 1e10m, and 123.456M are all of type decimal. This literal is converted to a decimal value by taking the exact value, and, if necessary, rounding to the nearest representable value using banker's rounding (ยง4.1.7). Any scale apparent in the literal is preserved unless the value is rounded or the value is zero (in which latter case the sign and scale will be 0). Hence, the literal 2.900m will be parsed to form the decimal with sign 0, coefficient 2900, and scale 3.
The NumberDecimalDigits property is used with the "F" and "N" standard format strings, not the ToString method called without a format string.
You can use:
Console.WriteLine(a.ToString("N", numberFormat));
Try this:
Console.WriteLine(String.Format("{0:0.00}", a));
Console.WriteLine(String.Format("{0:0.00}", b));
The output will have always 2 decimal cases. More examples here:
http://www.csharp-examples.net/string-format-double/

Read hex in C# using IO

I'm moving from C# to Java and can't seem to find any information on this. I'm trying to read if a file using hex, in Java I use...
String s = Integer.toHexString(hexIn);
if(s.length() < 2){
s = "0" + Integer.toHexString(hexIn);
}
As I'm sure you know thats so if the byte read in is one characater long it adds a zero to make it hex, I wanna do the same thing for c# so far i have...
StreamReader reader = new StreamReader(fileDirectory);
long stickNoteLength = fileDirectory.Length;
int hexIn;
String hex = "";
for (int i = 0; (hexIn = reader.Read()) != -1; i++)
{
}
Now I'm stuck, sorry if this is a simple question and thanks for you help :)
string hex = String.Format("{0:X2}", hexIn);
With this formatting mask you will get for numbers from 0 to 32 (for example):
00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F
I have added 2 (0:X2) because you mentioned that you are reading bytes.
Note, that for representing hex numbers also will be correct to add 0x at the string beginning:
string hex = String.Format("0x{0:X2}", hexIn);
Try this
hex = hexIn.ToString("X");
or
hex = Convert.ToString(hexIn,16);

Categories

Resources