I just tried out PVS-Studio on my C# project and it pointed out this function that screens for valid hexadecimal characters.  Originally the logic allowed all characters, but after fixing it I can't shake the feeling that there is a better way to do this.      string ValidHex()     {         string str = foo.Value;         for (int index = 0; index &lt; str.Length; index++)         {             if (Char.IsDigit(str[index]) == false)             {                 if ((str[index] &gt;= 'A' &amp;&amp; str[index] &lt;= 'F') ||                     (str[index] &gt;= 'a' &amp;&amp; str[index] &lt;= 'f'))                     continue;                 else                     return "Invalid Hex value";             }         }         return null;     }   I know I can't improve the time complexity, but is there a less awkward way to screen these ASCII values?
59820
What is the most efficient way in C# 2.0 to check each character in a string and return true if they are all valid hexadecimal characters and false otherwise? Example void Test() {     OnlyHexInString(&quot;123ABC&quot;); // Returns true     OnlyHexInString(&quot;123def&quot;); // Returns true     OnlyHexInString(&quot;123g&quot;); // Returns false }  bool OnlyHexInString(string text) {     // Most efficient algorithm to check each digit in C# 2.0 goes here }
3161
I need to validate an integer to know if is a valid enum value.  What is the best way to do this in C#?
50231
I have a context where I need to convert binary to hexadecimal and decimal and viceversa in a shell script. Can someone suggest me a tool for this?
94801
I have the following C# which simply replaces parts of the input string that look like EQUIP:19d005 into URLs, like this:  input = Regex.Replace(input, @"(EQUIP:)(\S+)", @"&lt;a title=""View equipment item $2"" href=""/EquipmentDisplay.asp?eqnum=$2""&gt;$1$2&lt;/a&gt;", RegexOptions.IgnoreCase);   The HTML ends up looking like this.  &lt;a title="View equipment item 19d005" href="/EquipmentDisplay.asp?eqnum=19d005"&gt;EQUIP:19d005&lt;/a&gt;   The only trouble is that the destination page expects the eqnum querystring to be all UPPERCASE so it returns the correct equipment when eqnum=19D005 but fails if it receives eqnum=19d005.  I guess I can modify and correct EquipmentDisplay.asp's errant requirement of uppercase values however, if possible I'd like to make the C# code comply with the existing classic ASP page by uppercasing the $2 in the Regex.Replace statement above.  Ideally, I'd like the HTML returned to look like this:  &lt;a title="View equipment item 19d005" href="/EquipmentDisplay.asp?eqnum=19D005"&gt;EQUIP:19d005&lt;/a&gt;   Notice although the original string was EQUIP:19d005 (lowercase), only the eqnum= value is uppercased.  Can it be done and if so, what's the tidiest way to do it?
64050
I'm trying to use String.Format("{0:c}", somevalue) in C# but am having a hard time figuring out how to configure the output to meet my needs. Here are my needs:   0 outputs to blank 1.00 outputs to $1.00 10.00 outputs to $10.00 100.00 outputs to $100.00 1000.00 outputs to $1,000.00   I've tried String.Format("{0:c}", somevalue) but for zero values it outputs $0.00 which is not what I want. I've also tried String.Format("{0:$0,0.00;$(0,0.00);#}", somevalue), but for 1.0 it outputs $01.00. String.Format("{0:$0.00;$(0.00);#}", somevalue) works for most cases, but when somevalue is 1000.00 the output is $1000.00.   Is there some format that will fit all 5 cases above? All of the documentation I've read only details the basics and doesn't touch on this type of scenario.
83428
Basically, how does the ^^^... notation work in LuaTeX and XeTeX, exactly?  In 8-bit TeX engines (recent TeX, eTeX, pdfTeX, at least), two consecutive identical catcode 7 characters (typically ^), followed by two lowercase hexadecimal digits, are converted before the tokenization step to the corresponding byte.  Namely, ^^6f is exactly equivalent to o: for instance, \sh^^6fw ^^6f will cause TeX to show the letter o.  There is also the notation with two ^ (identical catcode 7 characters), followed by any ascii character (but not two lowercase hexadecimal digits), which is replaced by the character obtained by either subtracting or adding 64 to the character code, remaining among ASCII characters (range 0 to 128).  Unicode-aware engines (I'm thinking of LuaTeX and XeTeX, there are perhaps other less known ones around) also provide ^^^^xxxx and ^^^^^xxxxx for characters whose hexadecimal representation has 4, or 5 digits.  But this does not seem to be done in the same way across engines.  For instance, both LuaTeX and XeTeX appear to accept the notation with 4, 5, or 6 carets followed by the same number of hexadecimal digits, but XeTeX also accepts it for 3, while LuaTeX doesn't. Compiling the following with pdfTeX, LuaTeX, and XeTeX gives different results.  \catcode0=12 \newlinechar=10 \def\loopshow#1{\message{\meaning #1^^J}\loopshow} \loopshow \/   ^^56   ^^^056   ^^^^0056   ^^^^^00056   ^^^^^^000056   ^^^^^^^0000056 {\end\iffalse} \fi} \bye   One weird fact about XeTeX (a bug?) is that  \show ^^^^^^010101   shows the character displaywidth.  My goal (there may be a better way to do this) is to provide a way to test whether passing a given list of tokens through \scantokens is safe.  For that, my plan is to go through the \detokenized token list one character at a time, applying TeX's rule for tokenizing (but no need to fully tokenize), and detecting begin-group and end-group tokens, as well as invalid characters.
81943
How does one parse an integer to string(char* || char[]) in C? Is there an equivalent to the Integer.parseInt(String) method from Java in C?
116773
The .NET Framework gives us the  method:  string s = string.Format("This {0} very {1}.", "is", "funny"); // s is now: "This is very funny."   I would like an "Unformat" function, something like:  object[] params = string.Unformat("This {0} very {1}.", "This is very funny."); // params is now: ["is", "funny"]   I know something similar exists in the ANSI-C library ( vs ).   The question: is there something similiar in C#?  Update: Capturing groups with regular expressions are not the solution I need. They are also one way. I'm looking for a system that can work both ways in a single format. It's OK to give up some functionality (like types and formatting info).
78747
I want to add two hexadecimal variables in a bash script.  I want them to start as hex and end in hex, not decimal.    What I've come up with so far is a bit of a round about hack. Is there a better or more elegant solution?  BASE=0xA000  OFFSET=0x1000  NEW_BASE=$(( $BASE + $OFFSET ))  NEW_BASE=`printf "0x%X\n" $NEW_BASE`  echo $NEW_BASE  0xB000
5329
I'm building a function to extend the Enum.Parse concept that  Allows a default value to be parsed in case that an Enum value is not found Is case insensitive  So I wrote the following: public static T GetEnumFromString&lt;T&gt;(string value, T defaultValue) where T : Enum {     if (string.IsNullOrEmpty(value)) return defaultValue;     foreach (T item in Enum.GetValues(typeof(T)))     {         if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;     }     return defaultValue; }  I am getting a Error Constraint cannot be special class System.Enum. Fair enough, but is there a workaround to allow a Generic Enum, or am I going to have to mimic the Parse function and pass a type as an attribute, which forces the ugly boxing requirement to your code. EDIT All suggestions below have been greatly appreciated, thanks. Have settled on (I've left the loop to maintain case insensitivity - I am using this when parsing XML) public static class EnumUtils {     public static T ParseEnum&lt;T&gt;(string value, T defaultValue) where T : struct, IConvertible     {         if (!typeof(T).IsEnum) throw new ArgumentException(&quot;T must be an enumerated type&quot;);         if (string.IsNullOrEmpty(value)) return defaultValue;          foreach (T item in Enum.GetValues(typeof(T)))         {             if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;         }         return defaultValue;     } }  EDIT: (16th Feb 2015) Christopher Currens has posted  below, which is well worth a look, and an upvote. I will remove this edit if the solution bubbles further up the page. EDIT 2: (13th Apr 2021) As this has now been addressed, and supported, since C# 7.3, I have changed the accepted answer, though full perusal of the top answers is worth it for academic, and historical, interest :)
2136
I am looking for a way to convert a long string (from a dump), that represents hex values into a byte array.  I couldn't have phrased it better than the person that posted .  But to keep it original, I'll phrase it my own way: suppose I have a string "00A0BF" that I would like interpreted as the  byte[] {0x00,0xA0,0xBf}   what should I do?  I am a Java novice and ended up using BigInteger and watching out for leading hex zeros. But I think it is ugly and I am sure I am missing something simple.
53059
I would like to format binary or hexadecimal numbers with a space separator at each 2 or 4 digit (or any other value like 8 digit or more).  A small picture is better than a long explanation, here is what I would like to do:    As you can see in this mwe, I use the fmtcount package with padzeroes:      \documentclass{article}     \usepackage[utf8]{inputenc}         \usepackage[T1]{fontenc}               \usepackage{fmtcount}     \begin{document}             Binary value : {\padzeroes[16]\binarynum{129}}$_{(2)}$ %             should display 0000 0000 1000 0001$_{(2)}$              Hexadecimal value: {\padzeroes[8]\Hexadecimalnum{65000}}$_{(16)}$ %             should display  00 00 FD E8$_{(2)}$     \end{document}   What I want to do is displaying numbers with various radix (2, 3, 7, 8, 10, 16) given a decimal number and format these numbers correctly with spaces and leading 0 (without having to perform the conversion by myself).  I already found some posts with similar questions, but none of them achieve this (they display number with thousand separators, like the numprint package, every 3 digits; or they do not make it automatic). Here are these posts :         EDIT two other linked questions:       I also prefer to use pdflatex.
82601
I'm trying to convert an incoming sting of 1s and 0s from stdin into their respective binary values (where a string such as "11110111" would be converted to 0xF7). This seems pretty trivial but I don't want to reinvent the wheel so I'm wondering if there's anything in the C/C++ standard libs that can already perform such an operation?
8886
I've seen this done in Borland's  environment, but I'm not sure how to go about it for a C# application I'm working on. Are there best practices or gotchas to look out for?
37193
What is the preferred way to remove spaces from a string in C++? I could loop through all the characters and build a new string, but is there a better way?
80556
What's going on?! Subtraction works fine until I get to 0.1 - 0.1. I'm in visual c# 2008 using the nonoba.com API.  Console.WriteLine("hit! " + Users[targetNum].character.health + " : " + player.character.profile.attackPower);  Users[targetNum].character.health -= player.character.profile.attackPower;  Console.WriteLine("health! " + Users[targetNum].character.health);   output:  hit! 0.1 : 0.1 health! 1.490116E-08   Thanks all - I might use the decimal type, as I'm normally adding/subtracting nice "round" numbers. For now I'll just go with:  if (Users[targetNum].character.health &lt;= 0.00001)   By the way I knew this wasn't really going to be a "bug" in c# - I thought it would either by a bug in my code or some lack of understanding, which it was.  Having read all the recommended reading, I'm going to conclude that my folly was due to normally using the ActionScript Number type, which maybe has a decimal rather than binary floating point - anyway, it would never give this output.
34299
How do you convert between hexadecimal numbers and decimal numbers in C#?