Is there any way of converting a string value (any content) to a number such that they both sort in the same way? I don't need to be able to convert the number back to a string. In fact it would be an advantage if it were impossible to convert it back.
I don't need to be able to sort any length of string. If a 64-bit long integer is used as the sort-value then I could trim the texts to a value that fits this number range.
I don't think there can be 100% correct way since sorting a string depends on the culture. For ex
int c1 = String.Compare("AA", "BB", false, CultureInfo.GetCultureInfo("en-US")); //return -1
int c2 = String.Compare("AA", "BB", false, CultureInfo.GetCultureInfo("da-DK")); //return 1
The closest thing I can think of is:
ulong l = BitConverter.ToUInt64(Encoding.UTF8.GetBytes(str), 0);
PS: pad str if its len is shorter than 8
You could take the first 8 bytes from the string, the 8 bytes would make up a ulong. It would only be 4 characters of the string with unicode, or 8 characters if you limit the strings to ASCII.
Related
I have an string which needs to be always 12 digits long
Its need starts with 'PSS1'
but need there to be always 12 characters and pad the difference with zero's
so if input is string1 = '300'
I would need the result = 'PSS100000300'
when the input length increase the number of zero padding decreases so the total of characters remains 12.
I've tried using .padleft or .ToString("D12")
This should work
string result = "PSS1".PadRight(12 - string1.Length,'0') + string1;
I realize that your original question said that you had a string, but if it were an int, you could do this with the ToString method on the int object.
int input = 300;
input.ToString("PSS100000000");
Which returns PSS100000300
Perhaps doesn't answer this specific question, but may potentially be useful for others.
I have a number
int number = 509; // integer
string bool_number = Convert.ToString(number, 2); // same integer converted to binary no
I want to bitwise or this number with hex values 0x01, 0x02, 0x04 and 0x08.
(e.g. something like this)
result = number | 0x01
How can I do it? Should I convert number to hex form or whats the right way?
You can use hexadecimal values as numeric literals...
int number = 509;
int hexNumber = 0x02;
int newNumber = number | hexNumber;
// whatever
string newNumberAsBinaryString = Convert.ToString(newNumber, 2);
Console.WriteLine(newNumber);
// etc.
If you need to input a hex string and convert it to a numeric type:
int num = Int32.Parse(hexString, System.Globalization.NumberStyles.HexNumber);
If you need to output a numeric type as hex:
Console.WriteLine(num.ToString("x"));
// or
Console.WriteLine("{0:x}", num);
See also MSDN's page on dealing with hex strings.
An int value isn't in any particular base. You can use bitwise operators on an int at any time - there's no need to convert it first. For example:
int a = 509;
int b = 0x1fd;
The variables a and b have exactly the same value here. I happen to have used a decimal literal to initialize a, and a hex literal to initialize b, but the effect is precisely the same.
So you can bitwise OR your ints at any time. Your example (adding a suitable declaration and semicolon to make it compile):
int result = number | 0x01;
will work just fine - you don't need to do anything to prepare number for this sort of usage. (Incidentally, this will do nothing, because the result of a bitwise OR of the numbers 509 and 1 is 509. If you write 509 in binary you get 111111101 - the bottom bit is already 1, so ORing in 1 won't change anything.)
You should avoid thinking in terms of things like "hex values", because there isn't really any such thing in C#. Numeric bases are only relevant for numbers represented as strings, which typically means either literals in source code, or conversions done at runtime. For example, if your program accepts a number as a command line argument, then that will arrive as a string, so you'll need to know its base to convert it correctly to an int. But once it's an int it's just an int - there's no such thing as a hex value or a decimal value for an int.
I have an int[]:
RXBuffer[0], RXBuffer[1],..., RXBuffer[9]
where each value represents an ASCII code, so 0x31 represents 1, 0x41 represents A.
How do I convert this to a 10 character string ?
So far I've tried Data = RxBuffer.ToString();. But it shows Data equals to System.Int32[] which is not what my data is.
How can I do this?
Assuming the "int array" is values in the 0-9 range (which is the only way that makes sense to convert an "int array" length 10 to a 10-character string) - a bit of an exotic way:
string s = new string(Array.ConvertAll(RXBuffer, x => (char)('0' + x)));
But pretty efficient (the char[] is right-sized automatically, and the string conversion is done just with math, instead of ToString()).
Edit: with the revision that makes it clear that these are actually ASCII codes, it becomes simpler:
string s = new string(Array.ConvertAll(RXBuffer, x => (char)x));
Although frankly, if the values are ASCII (or even unicode) it would be better to store it as a char[]; this covers the same range, takes half the space, and is just:
string s = new string(RXBuffer);
LolCoder
All you need is :
string.Join("",RXBuffer);
============== Or =================
int[] RXBuffer = {0,1,2,3,4,5,6,7,8,9};
string result = string.Join(",",RXBuffer);
have an interesting problem - I need to convert 2 (randomly) generated Guids into a string. Here are the constraints:
string max 50 charactes length.
only numbers and small letters can be used (0123456789abcdefghijklmnopqrstuvwxyz)
the algorithm has to be 2 way - need to be able to decode the encoded string into same 2 separate guids.
I've browsed a lot looking for toBase36 conversion bo so far no luck with Guid.
Any ideas? (C#)
First of all, you're in luck, 36^50 is around 2^258.5, so you can store the information in a 50 byte base-36 string. I wonder, though, why anybody would have to use base-36 for this.
You need to treat each GUID as a 128-bit number, then combine them into a 256-bit number, which you will then convert to a base-36 'number'. Converting back is doing the same in reverse.
Guid.ToByteArray will convert a GUID to a 16 byte array. Do it for both GUIDs and you have a 32 byte (which is 256 bits) array. Construct a BigInt from that array (there's a constructor), and then just convert that number to base-36.
To convert a number to base-36, do something like this (I assume everything is positive)
const string digits = "0123456789abcdefghijklmnopqrstuvwxyz";
string ConvertToBase36(BigInt number)
{
string result = "";
while(number > 0)
{
char digit = string[number % 36];
result += digit;
number /= 36;
}
}
Is there something similar to sprintf() in C#?
I would for instance like to convert an integer to a 2-byte byte-array.
Something like:
int number = 17;
byte[] s = sprintf("%2c", number);
string s = string.Format("{0:00}", number)
The first 0 means "the first argument" (i.e. number); the 00 after the colon is the format specifier (2 numeric digits).
However, note that .NET strings are UTF-16, so a 2-character string is 4 bytes, not 2
(edit: question changed from string to byte[])
To get the bytes, use Encoding:
byte[] raw = Encoding.UTF8.GetBytes(s);
(obviously different encodings may give different results; UTF8 will give 2 bytes for this data)
Actually, a shorter version of the first bit is:
string s = number.ToString("00");
But the string.Format version is more flexible.
EDIT: I'm assuming that you want to convert the value of an integer to a byte array and not the value converted to a string first and then to a byte array (check marc's answer for the latter.)
To convert an int to a byte array you can use:
byte[] array = BitConverter.GetBytes(17);
but that will give you an array of 4 bytes and not 2 (since an int is 32 bits.)
To get an array of 2 bytes you should use:
byte[] array = BitConverter.GetBytes((short)17);
If you just want to convert the value 17 to two characters then use:
string result = string.Format("{0:00}", 17);
But as marc pointed out the result will consume 4 bytes since each character in .NET is 2 bytes (UTF-16) (including the two bytes that hold the string length it will be 6 bytes).
It turned out, that what I really wanted was this:
short number = 17;
System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream);
writer.Write(number);
writer.Flush();
The key here is the Write-function of the BinaryWriter class. It has 18 overloads, converting different formats to a byte array which it writes to the stream. In my case I have to make sure the number I want to write is kept in a short datatype, this will make the Write function write 2 bytes.