Converting string "0x1A" to sbyte - c#

I'm getting the exception:
Input string was not in a correct format.
at runtime for the following code snippet.
string str= "0x1A";
sbyte value= Convert.ToSByte(str);
Can anyone help in fixing this?

Convert.ToSByte takes an argument int fromBase to specify the base you're converting from.
In your case you have to do the following:
sbyte s = Convert.ToSByte(str, 16); // s == 26
You can read more about different bases (also called radix) in this Wikipedia article.

If you look up in the documentation of ToSByte under the section Exceptions you will find the condition under which this exception is thrown:
value does not consist of an optional sign followed by a sequence of digits (0 through 9).
You value is written in HEX format, meaning to the base of 16. The input string contains not only "digits (0 through 9)". For that you will need another overload of this method in which you can specify this.
If you look at this overload of Convert.ToSByte Method (String, Int32) you can see that it:
Converts the string representation of a number in a specified base to an equivalent 8-bit signed integer.
The second parameter is :
fromBase
Type: System.Int32
The base of the number in value, which must be 2, 8, 10, or 16.
So specifying the base will releave you from the exception:
string str = "0x1A";
sbyte value = Convert.ToSByte(str, 16);

Related

assigning a string's chars to an int array assigns the wrong value

if I assing a string with
string = "12";
and check its value with
Console.Write(string[0] + string[1]);
it returns 12 as intended.
but if I assign string[0] to an int array via
int[0] = string[0];
and check its value via
Console.Write(int[0]);
it returns 49.
even if I used Convert.ToInt32() while assigning, it still returned 49.
the code
the result
Can you help me out here?
It is returning 49 because you are trying to convert the value 1 to integer and the ASCII value of 1 is 49. if you want to print the value as 1 to need to use string only, then you can use the code similar to this int.Parse(stringValue); or you can use TryParse method as well.
You are casting the char '1' into an int which works. Which according to the ASCII table is 49.
For example assigning 'A' to int[0] would set its value to 65.
You must just use int.Parse().

Convert.ToInt64 fails when value is "0.00000"

5 my code is like this
protected long Getvalue()
{
DataTable dt = GetDataBaseValue();
if (dt.Rows.Count > 0)
{
return Convert.ToInt64(dt.Rows[0]["BALANCE"].ToString());
}
return 0;
}
dt.Rows[0]["BALANCE"].ToString()=0.00000 I am getting the error here
PS: I tried to do this return long.Parse(...) and I got the same error
The problem is that "0.00000" is a String, which is an invalid format for "parsing to a long"1.
However, it may be sufficient to omit the ToString() conversion, and thus the above error, depending on what type the database actually returns. If the database returns an appropriate double/float/decimal then the following "Will Work", even if losing precision.
// Source is a double
Convert.ToInt64(0.0d) // -> 0
Convert.ToInt64(0.5d) // -> 0 (half-even rounding)
Convert.ToInt64(1.5d) // -> 2 (half-even rounding)
Convert.ToInt64(double.MaxValue) // -> OverflowException
// Source is a string
Convert.ToInt64("0") // -> 0
Convert.ToInt64("0.0") // -> FormatException: "not in a correct format"
If, for some uncorrectable reason, the database returns a String in the given format, it should suffice to first convert the string to a double/decimal (which do support such a format) and then to a long. Similar overflow and loss of precision cases are possible.
long v = (long)Convert.ToDecimal(dt.Rows[0]["BALANCE"]);
By default, .NET will parse integer values (e.g. int, long) from strings only when they conform to the pattern \s*[-+]?\d+\s* and will throw a FormatException otherwise; this is discussed in more detail in the linked documentation.
0.00000 is not a valid value for Int64. Perhaps you intended to use a Decimal (it looks like a currency amount) or otherwise truncate/round the value first?
Use Decimal.Parse("0.0000"); this is used for currency Not Long or Int64

convert a string length to a hex value to add to List<byte>

I have a List that I'm adding 3 bytes to one of which is the length of a string that I'm dynamically passing to my method. How can I determine the length of that string and convert the int into a value that would be accepted in my list.add() method.
Code below:
string myString = "This is a sample string...I need its length";
int theLength = myString.Length;
List<byte> lb = new List<byte>();
lb.Add(0x81);
lb.Add(theLength); // this doesn't work
lb.Add(0x04);
TIA
Try this:
lb.AddRange(BitConverter.GetBytes(theLength))
Of course, you may decide you only need the least significant bit, in which case you could do a simple cast, or index into the result of GetBytes(), which will be 4 bytes long in this case.
More on BitConverter:
http://msdn.microsoft.com/en-us/library/system.bitconverter.getbytes.aspx
Provided the string's length is within the byte range:
lb.Add((byte)theLength);
You have to cast your length into a byte:
lb.Add((byte)theLength);
But as you might guess, your length won't always fit into a single byte. Be more specific about what you expect to do with your list of bytes, we might could provide a better answer (such as using BinaryReader/BinaryWriter instead of a list of bytes).

Is there a C# function that formats a 64bit "Unsigned" value to its equivalent binary value?

To format/display a number to its equivalent binary form (in C#), I have always simply called:
Convert.ToString(myNumber, 2);
Today, I just realized that the .ToString() overload that I have been calling does not support values that are greater than 9223372036854775807. Note the .ToString() overload's signature is: .ToString(long, int). Where "long" is a 64bit signed value which max's out at 9223372036854775807.
To put it another way, using C#, when I run this:
Convert.ToString(9223372036854775808,2);
It's no surprise (due to the signature) that I receive this exception message:
The best overloaded method match for 'System.Convert.ToString(object,
System.IFormatProvider)' has some invalid arguments
- Argument 2: cannot convert from 'int' to 'System.IFormatProvider'
My question: Is there a .NET function that allows us to convert values greater than 9223372036854775807 to their equivalent binary format?
You can call it unsigned or signed, but its the same if you look at it bitwise!
So if you do this:
Convert.ToString((long)myNumber,2);
you would get the same bits as you would if there were ulong implementation of Convert.ToString(), and thats why there is none... ;)
Therefore, ((long)-1) and ((ulong)-1) looks the same in memory.
Unfortunately there's no direct .NET equivalent like Convert.ToString(ulong, int). You'll have to make your own, like the following:
public static string ConvertToBinary(ulong value){
if(value==0)return "0";
System.Text.StringBuilder b=new System.Text.StringBuilder();
while(value!=0){
b.Insert(0,((value&1)==1) ? '1' : '0');
value>>=1;
}
return b.ToString();
}
public static string UInt64ToBinary(UInt64 input)
{
UInt32 low = (UInt32) (input & 0xFFFFFFFF);
UInt32 high = (UInt32) (input & 0xFFFFFFFF00000000) >> 32;
return $"{Convert.ToString(high, 2).PadLeft(32, '0')}{Convert.ToString(low, 2).PadLeft(32, '0')}";
}

C#: Convert a UInt16 in string format into an integer(decimal)

Here's the problem.
I ,for example,have a string "2500".Its converted from byte array into string.I have to convert it to decimal(int).
This is what I should get:
string : "2500"
byte[] : {0x25, 0x00}
UInt16 : 0x0025 //note its reversed
int : 43 //decimal of 0x0025
How do I do that?
Converting from hex string to UInt16 is UInt16.Parse(s, NumberStyles.AllowHexSpecifier).
You'll need to write some code to do the "reversal in two-digit blocks" though. If you have control over the code that generates the string from the byte array, a convenient way to do this would be to build the string in reverse, e.g. by traversing the array from length - 1 down to 0 instead of in the normal upward direction. Alternatively, assuming that you know it's exactly a 4 character string, s = s.Substring(2, 2) + s.Substring(0, 2) would do the trick.
It might be better to explicitly specify what base you want with Convert.ToUInt16.
Then, you can flip it around with IPAddress.HostToNetworkOrder (though you'll have to cast it to an int16, then cast the result back to a uint16.
there is a special class for conversion : Convert
to convert from string to uint16 use the following method: Convert.ToUInt16
for difference on int.parse and Convert.ToInt32 is explained in this page
and the msdn site for Convert.ToUInt16 here
Assuming your string is always 4 digits long.
You can get away with one string variable but I'm using multiple ones for readability.
string originalValue = "2500";
string reverseValue = originalValue.Substring(2, 2) + originalValue.Substring(0, 2);
string hexValue = Convert.ToUInt16(reverseValue, 16).ToString();
int result = Convert.ToInt32(hexValue, 10);

Categories

Resources