Convert string to short - c#

I have a string that contains the next value: 0x6007.(stringToShort)
I want to convert this string to short var, however, when I attempt to convert it the next way:
short s = ((short)Convert.ToUInt16(stringToShort, 16));
then s equals to 24583 and not to 0x6007 as I need.
Can anyone help?

Values like "0x6007" and "24583" are for human consumption. They are textual representations of a number, and are meaningful only for humans.
As far as the computer is concerned, when dealing with actual numbers, it only understands binary (and even there, only in an abstract sense…it doesn't literally store the binary digits 0s and 1s).
Any time you ask the computer what number it's thinking of, it will convert from that binary-based representation to a human-readable representation (even if binary…we puny humans can't see the state of the bits in the computer and have to ask the computer to translate them to a visual representation).
When you store the value 0x6007 in (for example) a short variable, that variable contains the value 0x6007. It also contains the value 24583. Oh, and it also contains the value 110000000000111 (binary), and the value 60007 (octal), and even the value 12287 (base twelve). Because what the computer is storing is not any of those specific representations of numbers, but rather its own internal representation of the magnitude any of those human-readable numbers represent.
But they are all the same. And when you parse a human-readable string like "0x6007", you do get exactly that value in the variable into which you stored the result, i.e. the computer's internal representation of a number having the same magnitude.
By default, if you ask the computer to tell you what that value is, it will give you the decimal representation of "24583". But if you want the hexadecimal representation, you need only ask nicely and the computer will give that to you instead (e.g. switch the numeric display format in your debugger, or use the "X" numeric format specifier in string.Format(), Console.WriteLine(), etc.).

Related

Format number type long into 8 digits

I have two variables of type long?. I need to use long1 variable and, if null, take long2.
//long1 format: 20130104
//long2 format: 2.01301071520553E16
var target = long1 ?? long2;
The variable target will be used in a query to find an exact match with a varibale in format "xxxxxxxx" (8 digits, same format as long1).
Is there any elegant way to cut the long2 digits into the same format as long1 without having to parse it into a string first? Since I will have to process the target variable as long and not a string, therefore I would avoid a second parse from string to long again.
Just take as many digits of accuracy as you require when you print the variable later on. It doesn't matter if it has 100 digits, it's only used for calculations. When you are ready to display it use:
String.Format("MyLong: {0:0.00000000}", long);
Or however you want it to look.

Happy 3501.ToString("X") day!

In C#, is there a way to convert an int value to a hex value without using the .ToString("X") method?
Your question is plain wrong (no offense intended). A number has one single value. Hex, Decimal, Binary, Octal, etc. are just different representations of one same integral number. Int32 is agnostic when it comes to what representation you choose to write it with.
So when you ask:
is there a way to convert an int value to a hex value
you are asking something thast doesn't make sense. A valid question would be: is there anyway to write a integer in hexadecimal representation that doesn't involve using .ToString("X")?
The answer is not really. Someway or the other (directly or not by you), .ToString("X") or some other flavor of ToString() will be called to correctly format the string representing the value.
And when you think of hexadecimal as a respresentation (a formatted string) of a given number, then .ToString() does make sense.
Use Convert.ToString( intValue, 16 );
It can be used to convert between any common numeric base, i.e., binary, octal, decimal and hexadecimal.

Float to String format specifier

I have some float values I want to convert to a string, I want to keep the formatting the same when converting, i.e. 999.0000(float) -> 999.0000(String). My problem is when the values contain an arbitrary number of zeroes after the decimal point, as in the previous example, they are stripped away when converting to a string, so the result I actually end up with is 999.
I looked at the format specifiers for the toString() method on MSDN, the RoundTrip ('R') specifier looks like it will produce what I want, but it is only supported for Single, Double and BigInt variables. Is there a format specifier like this for float variables?? Or would it be easier to just convert the values to doubles?
UPDATE: Just for clarity, the reason why I want to keep the trailing zeroes is because I'm doing a comparison of decimal places, i.e. I'm comparing the number of digits after the decimal place between two values. So for example, 1.00 and 1.00000 have a different number of digits after the decimal point. I know it's a strange request, it's for work and the requirement is coming from on high.
UPDATE 2-3-11:
I was thinking about this too hard, I'm reading the numbers from a txt file and then parsing them as floats, I'm going to modify the program to check whether the string values are decimals or whole numbers. Sorry for wasting your time, although this was very insightful.
Use ToString() with this format:
12345.678901.ToString("0.0000"); // outputs 12345.6789
12345.0.ToString("0.0000"); // outputs 12345.0000
Put as much zero as necessary at the end of the format.
Firstly, as Etienne says, float in C# is Single. It is just the C# keyword for that data type.
So you can definitely do this:
float f = 13.5f;
string s = f.ToString("R");
Secondly, you have referred a couple of times to the number's "format"; numbers don't have formats, they only have values. Strings have formats. Which makes me wonder: what is this thing you have that has a format but is not a string? The closest thing I can think of would be decimal, which does maintain its own precision; however, calling simply decimal.ToString should have the effect you want in that case.
How about including some example code so we can see exactly what you're doing, and why it isn't achieving what you want?
You can pass a format string to the ToString method, like so:
ToString("N4"); // 4 decimal points Number
If you want to see more modifiers, take a look at MSDN - Standard Numeric Format Strings
In C#, float is an alias for System.Single (a bit like intis an alias for System.Int32).

Efficient Hex Manipulation

I have a byte array represented by hex values, these are time durations. The data could be converted to integer values and multiplied by a constant to get the timings. The decoding of the data will be saved to a file as a series of hex strings. What would be an efficient way of manipulating hex values?
I was looking at performance issues when dealing with data formats, as I have to work with more than one format at different stages (calculations, data display, etc.). Most examples show the conversion from byte[] to hex string ("1A 3C D4"), and viceversa, but I was looking for an alternative, which is to convert to Int16 and use char[] array.
You don't have a byte array representing hex values. You have a byte array representing numbers. The base you represent a number in is only relevant when you're representing it.
To put it a different way: if you thought of your byte array as representing decimal integers instead, how do you imagine it would be different? Is my height different if I represent it in feet and inches instead of metres?
Now, if you're trying to represent 16-bit numbers, I'd suggest that using a byte array is a bad idea. Use a ushort[] or short[] instead, as those are 16-bit values. If you're having trouble getting the data into an array like that, please give details... likewise if you have any other problems with the manipulation. Just be aware that until you're writing the data out as text, there's really no such concept as which base it's in, as far as the computer is concerned.
(Note that this is different for floating point values, where the data really would be different between a decimal and a double, for example... there, the base of representation is part of the data format. It's not for integers. Alternatively, you can think of all integers as just being binary until you decide to format them as text...)
From MSDN:
The hexadecimal ("X") format specifier
converts a number to a string of
hexadecimal digits. The case of the
format specifier indicates whether to
use uppercase or lowercase characters
for hexadecimal digits that are
greater than 9. For example, use "X"
to produce "ABCDEF", and "x" to
produce "abcdef". This format is
supported only for integral types.
The precision specifier indicates the
minimum number of digits desired in
the resulting string. If required, the
number is padded with zeros to its
left to produce the number of digits
given by the precision specifier.
byte x = 60;
string hex = String.Format("0x{0:X4}", x);
Console.WriteLine(hex); // prints "0x003C"

Why does (string)int32 always throw: Cannot convert type 'int' to 'string'

Why does (string)int32 always throw: Cannot convert type 'int' to 'string'
public class Foo
{
private int FooID;
public Foo()
{
FooID = 4;
string s = (string)FooID; //throws compile error
string sss = FooID.ToString(); //no compile error
}
}
Because there is no type conversion defined from Int32 to string. That's what the ToString method is for.
If you did this:
string s = (string)70;
What would you expect to be in s?
A. "70" the number written the way humans would read it.
B. "+70" the number written with a positive indicator in front.
C. "F" the character represented by ASCII code 70.
D. "\x00\x00\x00F" the four bytes of an int each separately converted to their ASCII representation.
E. "\x0000F" the int split into two sets of two bytes each representing a Unicode character.
F. "1000110" the binary representation for 70.
G. "$70" the integer converted to a currency
H. Something else.
The compiler can't tell so it makes you do it the long way.
There are two "long ways". The first is to use one of the the Convert.ToString() overloads something like this:
string s = Convert.ToString(-70, 10);
This means that it will convert the number to a string using base 10 notation. If the number is negative it displays a "-" at the start, otherwise it just shows the number. However if you convert to Binary, Octal or Hexadecimal, negative numbers are displayed in twos complement so Convert.ToString(-7, 16) becomes "ffffffba".
The other "long way" is to use ToString with a string formatter like this:
string s2 = 70.ToString("D");
The D is a formatter code and tells the ToString method how to convert to a string. Some of the interesting codes are listed below:
"D" Decimal format which is digits 0-9 with a "-" at the start if required. E.g. -70 becomes "-70".
"D8" I've shown 8 but could be any number. The same as decimal, but it pads with zeros to the required length. E.g. -70 becomes "-00000070".
"N" Thousand separators are inserted and ".00" is added at the end. E.g. -1000 becomes "-1,000.00".
"C" A currency symbol is added at the start after the "-" then it is the same as "N". E.g. Using en-Gb culture -1000 becomes "-£1,000.00".
"X" Hexadecimal format. E.g. -70 becomes "46".
Note: These formats are dependent upon the current culture settings so if you are using en-Us you will get a "$" instead of a "£" when using format code "C".
For more information on format codes see MSDN - Standard Numeric Format Strings.
When performing a cast operation like (string)30, you're basically telling the computer that "this object is similar enough to the object I'm casting to that I won't lose much (or any) data/functionality".
When casting a number to a string, there is a "loss" in data. A string can not perform mathematical operations, and it can't do number related things.
That is why you can do this:
int test1 = 34;
double test2 = (double)test1;
But not this:
int test1 = 34;
string test2 = (string)test1;
This example isn't perfect since (IIRC) the conversion here is implicit, however the idea is that when converting to a double, you don't lose any information. That data type can still basically act the same whether it's a double or an int. The same can't be said of an int to a string.
Casting is (usually) only allowed when you won't lose much functionality after the conversion is done.
The .ToString() method is different from casting because it's just a method that returns a string data type.
Just another note: In general, if you want to do an explicit conversion like this (and I agree with many other answers here as to why it needs to be an explicit conversion) don't overlook the Convert type. It is designed for these sorts of primitive/simple type conversions.
I know that when starting in C# (and coming from C++) I found myself running into type casts that seemed like they should have worked. C++ is just a bit more liberal when it comes to this sort of thing, so in C# the designers wanted you to know when your type conversion were ambiguous or ill-advised. The Convert type then fills in the gaps by allowing you to explicitly convert and understand the side-effects.
Int doesn't have an explicit operator to string. However, they have Int32.ToString();. Maybe you can create one with Extension methods, if you really want to.
Because C# does not know how to convert int to string, the library (.ToString) does.
Int32 can't be casted to string because C# compiler doesn't know how to converter from one type to another.
Why is that, you will ask the reason is simple int32 is type integer/numerical and string is, oh well type string/characters. You may be able to convert from numerical type to another numerical type (ex. float to int, but be warned possible loss of accuracy).
If all possible casts where coded in the compiler the compiler would become too slow and certainly would miss much of the possible casts created for user defined types which is a major NO NO.
So the workaround is that any object in C# has a function inherited .ToString() that knows how to handle every type because .ToString() is specifically coded for the specific type, and as you guessed by now returns a string.
After all Int32 type is some bits in memory (32 bits to be exact) and string type is another pile of bits (how many bits depends on how much has been allocated) the compiler/runtime doesn't know anything just by itself looking at that data until now. .ToString() function accesses the specific metadata needed to convert from one to the other.
I just found the answer. ToString works fine on an int variable. You just have to make sure you add the brackets.
ie...
int intMyInt=32;
string strMyString = intMyInt.ToString();
VB .net is perfectly capable of casting from an int to string... in fact so is Java. Why should C# have a problem with it? Sometimes it is necessary to use a number value in calculations and then display the result in a string format. How else would you manage to display the result of a calculation in a TextBox?
The responses given here make no sense. There must be a way to cast an int as a string.

Categories