String.Format for Hex - c#

With below code, the colorsting always gives #DDDD. Green, Red and Space values int he How to fix this?
string colorstring;
int Blue = 13;
int Green = 0;
int Red = 0;
int Space = 14;
colorstring = String.Format("#{0:X}{0:X}{0:X}{0:X}", Blue, Green, Red, Space);

The number 0 in {0:X} refers to the position in the list or arguments. In this case 0 means use the first value, which is Blue. Use {1:X} for the second argument (Green), and so on.
colorstring = String.Format("#{0:X}{1:X}{2:X}{3:X}", Blue, Green, Red, Space);
The syntax for the format parameter is described in the documentation:
Format Item Syntax
Each format item takes the following form and consists of the following components:
{ index[,alignment][:formatString]}
The matching braces ("{" and "}") are required.
Index Component
The mandatory index component, also called a parameter specifier, is a number starting from 0 that identifies a corresponding item in the list of objects. That is, the format item whose parameter specifier is 0 formats the first object in the list, the format item whose parameter specifier is 1 formats the second object in the list, and so on.
Multiple format items can refer to the same element in the list of objects by specifying the same parameter specifier. For example, you can format the same numeric value in hexadecimal, scientific, and number format by specifying a composite format string like this: "{0:X} {0:E} {0:N}".
Each format item can refer to any object in the list. For example, if there are three objects, you can format the second, first, and third object by specifying a composite format string like this: "{1} {0} {2}". An object that is not referenced by a format item is ignored. A runtime exception results if a parameter specifier designates an item outside the bounds of the list of objects.
Alignment Component
The optional alignment component is a signed integer indicating the preferred formatted field width. If the value of alignment is less than the length of the formatted string, alignment is ignored and the length of the formatted string is used as the field width. The formatted data in the field is right-aligned if alignment is positive and left-aligned if alignment is negative. If padding is necessary, white space is used. The comma is required if alignment is specified.
Format String Component
The optional formatString component is a format string that is appropriate for the type of object being formatted. Specify a standard or custom numeric format string if the corresponding object is a numeric value, a standard or custom date and time format string if the corresponding object is a DateTime object, or an enumeration format string if the corresponding object is an enumeration value. If formatString is not specified, the general ("G") format specifier for a numeric, date and time, or enumeration type is used. The colon is required if formatString is specified.
Note that in your case you only have the index and the format string. You have not specified (and do not need) an alignment component.

You can also pad the characters left by including a number following the X, such as this: string.format("0x{0:X8}", string_to_modify), which yields "0x00000C20".

Translate composed UInt32 color Value to CSS in .NET
I know the question applies to 3 input values (red green blue). But there may be the situation where you already have a composed 32bit Value. It looks like you want to send the data to some HTML CSS renderer (because of the #HEX format). Actually CSS wants you to print 6 or at least 3 zero filled hex digits here. so #{0:X06} or #{0:X03} would be required. Due to some strange behaviour, this always prints 8 digits instead of 6.
Solve this by:
String.Format("#{0:X02}{1:X02}{2:X02}", (Value & 0x00FF0000) >> 16, (Value & 0x0000FF00) >> 8, (Value & 0x000000FF) >> 0)

More generally.
byte[] buf = new byte[] { 123, 2, 233 };
string s = String.Concat(buf.Select(b => b.ToString("X2")));

If we have built in functions to convert your integer values to COLOR then why to worry.
string hexValue = string.Format("{0:X}", intColor);
Color brushes = System.Drawing.ColorTranslator.FromHtml("#"+hexValue);

Related

Formatting Output in C# With Curly Brackets

What do the values within the curly brackets do in this example?
{
double price = 1234.56
Console.WriteLine("TV{0:F0} is {1:C}" , 2, price);
Console.Read();
}
Basically the first number ist the index of the argument (0 means 2, 1 means price in your example).
The value after the colon is one of the Standard Numeric Format Strings, see MSDN-Docs for available options.
{0:F0} prints 2 because parameter 0 is 2 and format is Fixed Point with zero decimal places (F0)
{1:C} prints $1234,56becaus parameter 1 (price) is 1234.56 and format is Currency (C)
This example uses only Format Strings for numerics, there are also Standard Format Strings for DateTime and so on..
What do the values within the curly brackets do in this example?
They are format specifications for the values provided. Essentially, it instructs the Console.WriteLine function how to format the values as strings for output to the console. Here is a .NET fiddle that exemplifies this.
The MSDN documentation has an extensive example that shows how these work.
{0:F0} takes the given 2 int value, and simply prints it as 2, "2"
{1:C} takes the given 1234.56 double value and treats it as currency, "$1,234.45".
The 0 and 1 are significant as they are the zero-based array indicator of the location in which the parameters map to the string formatting. For example, the below demonstrates outputs from altering the arguments to better visualize the impact.
Console.WriteLine("TV{0:F0} is {1:C}", 2, price); // Prints TV2 is $1,234.56
Console.WriteLine("TV{0:F0} is {1:C}", price, 2); // Prints TV1234 is $2.00

What is the optional argument in C# interpolated string for?

Interpolated strings is one of the new features of C# 6.0.
According to MSDN, the syntax of the embedded C# expressions can contain an optional, comma-separated value, deemed as <optional-comma-field-width> in the documentation.
Unfortunately I didn't find what this field is for.
From its name one might think that this value sets the maximal size of the "interpolated" field, but when I try the following expression:
var p = Process.GetCurrentProcess();
Console.WriteLine($"Process name is {p.ProcessName, 5}");
I get the following output:
Process name is LINQPad.UserQuery
It's the minimum width to use for that field, not the maximum. Since your string is longer than the 5 characters you specify for the width, the field is extended to the length of your string. You'll see the difference more dramatically with a longer width:
var p = Process.GetCurrentProcess();
$"Process name is {p.ProcessName, 50}".Dump();
yields:
Process name is LINQPad.UserQuery
A positive field size is right-justified; a negative field size is left-justified.
The documentation is better on the Composite Formatting page of MSDN:
The optional alignment component is a signed integer indicating the
preferred formatted field width. If the value of alignment is less
than the length of the formatted string, alignment is ignored and the
length of the formatted string is used as the field width. The
formatted data in the field is right-aligned if alignment is positive
and left-aligned if alignment is negative. If padding is necessary,
white space is used. The comma is required if alignment is specified.
The number is the alignment, documented in the Alignment Component here.
The formatted data in the field is right-aligned if alignment is
positive and left-aligned if alignment is negative.
In your example, alignment will pad the p.ProcessName with spaces if it is less than 5 characters long. Where string length is less than the absolute value of alignment (like in your example), alignment has no effect.
Example
var text = "MyText";
Console.WriteLine($"x{text}x");
Console.WriteLine($"x{text, 3}x");
Console.WriteLine($"x{text, 10}x");
Console.WriteLine($"x{text, -10}x");
Result
xMyTextx
xMyTextx
x MyTextx
xMyText x

Printing Hexadecimals as Hexadecimals in C#?

I need to send an array of bytes to a hardware (SDZ16 matrix) using a Serial Port. The trick is in the fact that that hardware expects strings of hexadecimal and ASCII characters.
When assigning values to the array of bytes, even if I set the bytes to an explicit hexadecimal value
(bytes[0] = 0xF2, for instance), it will print the equivalent decimal value (242 instead of F2).
I am suspicious that the problem is in the Console.WriteLine(); which when printing each byte sets them by default as integers(?) How does C# keep track that there is an Hexadecimal value inside an int?
If I assign bytes[0] = 0xF2; will the hardware understand it in hexadecimal even if Console.WriteLine(); shows differently will testing?
If you want to get a string representation in hex format you can do so by using a corresponding numeric format string:
byte value = 0xF2;
string hexString = string.Format("{0:X2}", value);
Note that Console.WriteLine has an overload that takes a format string and a parameter list:
Console.WriteLine("{0:X2}", value);
Update: I just had a glimpse at the documentation here, and it seems that you need to send commands by providing the corresponding ASCII representation in the form of a string. You can get the ASCII representation using:
byte value = 0x01;
string textValue = value.ToString().PadLeft(2, '0');
byte[] ascii = Encoding.ASCII.GetBytes(textValue)
My tip would be to carefully check the documentation of your equipment to find out which exact format is expected.
it will print the equivalent decimal value (242 instead of F2).
Yes because 0xF2 is still 242. It is just an hexadecimal notation. Most comman prefix is 0x in this notation. Even if you use debugger, you can see it's decimal notation.
I am suspicious that the problem is in the Console.WriteLine(); which
when printing each byte sets them by default as integers(?)
No, Console.WriteLine() method nothing do here.
How does C# keep track that there is an Hexadecimal value inside an
int?
There is no such a thing as Hexadecimal value inside an int. It is just a notation.
If you wanna hexadecimal notation of a number, you can use The hexadecimal "X" format specifier like;
byte b = 0xF2;
Console.WriteLine(b.ToString("X")); //F2
If you wanna get with prefix; you can do;
byte b = 0xF2;
Console.WriteLine("0x{0}", b.ToString("X")); //0xF2

Console.Write syntax: what does the format string "{0, -25}" mean

I am writing C# code
Console.Write("{0,-25}", company);
In above code what does this "{0,-25}" thing mean?
You mention it's hard to see what it does: that's because it adds spaces and those are difficult to see in the console. Try adding a character directly before and after the output so you can more clearly see the space, like the examples below:
This
Console.WriteLine("[{0, -25}]", "Microsoft"); // Left aligned
Console.WriteLine("[{0, 25}]", "Microsoft"); // Right aligned
Console.WriteLine("[{0, 5}]", "Microsoft"); // Ignored, Microsoft is longer than 5 chars
Will result in this (with spaces)
[Microsoft ]
[ Microsoft]
[Microsoft]
Which looks like this in the console window:
Read about string formatting on MSDN, specifically composite formatting. The '-25;' specifies the alignment component.
Alignment Component The optional alignment component is a signed
integer indicating the preferred formatted field width. If the value
of alignment is less than the length of the formatted string,
alignment is ignored and the length of the formatted string is used as
the field width. The formatted data in the field is right-aligned if
alignment is positive and left-aligned if alignment is negative. If
padding is necessary, white space is used. The comma is required if
alignment is specified.
That 'thing' is a composite formatting string. See the remarks here and this article here.
It is used for alignment.
Check this so that you can get
Console.Write("Company = |{0,-25}|", company);
string company1="ABC Inc";
string company2="XYZ International Inc";
Console.Write("{0,-10}", company1);//o/p [ABC Inc...]
Console.Write("{0,10}", company1);o/p [...ABC Inc]
Console.Write("{0,-10}", company2);o/p [XYZ International Inc]
//In the first Write(),output is LEFT justified in an output field width of 10
//In second Write(), output is RIGHT justified in an output field width of 10
//In the third Write(), output width is ignored , since the company2 name has more than 10 characters.

How to force a sign when formatting an Int in c#

I want to format an integer i (-100 < i < 100), such that:
-99 formats as "-99"
9 formats as "+09"
-1 formats as "-01"
0 formats as "+00"
i.ToString("00")
is close but does not add the + sign when the int is positive.
Is there any way to do this without explicit distinguishing between
i >= 0 and i < 0?
Try this:
i.ToString("+00;-00;+00");
When separated by a semicolon (;) the first section will apply to positive values, the second section will apply to negative values, the third section will apply to zero (0).
Note that the third section can be omitted if you want zero to be formatted the same way as positive numbers. The second section can also be omitted if you want negatives formatted the same as positives, but want a different format for zero.
Reference: MSDN Custom Numeric Format Strings: The ";" Section Separator
You might be able to do it with a format string like so..
i.ToString("+00;-00");
This would produce the following output..
2.ToString("+00;-00"); // +02
(-2).ToString("+00;-00"); // -02
0.ToString("+00;-00"); // +00
Take a look at the MSDN documentation for Custom Numeric Format Strings
Try something like this:
i.ToString("+00;-00");
Some examples:
Console.WriteLine((-99).ToString("+00;-00")); // -99
Console.WriteLine(9.ToString("+00;-00")); // +09
Console.WriteLine((-1).ToString("+00;-00")); // -01
Console.WriteLine((0).ToString("+00;-00")); // +00

Categories