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);
Related
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.
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.
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;
}
}
I got a boolean list with 92 booleans, I want the list to be converted to a string, I thought I ll take 8 booleans(bits) and put them in a Byte(8 bits) and then use the ASCII to convert it the byte value to a char then add the chars to a string. However after googeling for more then 2 hours, no luck atm. I tried converting the List to a Byte list but it didn t work either ^^.
String strbyte = null;
for (int x = 0; x != tmpboolist.Count; x++) //tmpboolist is the 90+- boolean list
{
//this loop checks for true then puts a 1 or a 0 in the string(strbyte)
if (tmpboolist[x])
{
strbyte = strbyte + '1';
}
else
{
strbyte = strbyte + '0';
}
}
//here I try to convert the string to a byte list but no success
//no success because the testbytearray has the SAME size as the
//tmpboolist(but it should have less since 8 booleans should be 1 Byte)
//however all the 'Bytes' are 48 & 49 (which is 1 and 0 according to
//http://www.asciitable.com/)
Byte[] testbytearray = Encoding.Default.GetBytes(strbyte);
PS If anyone has a better suggestion on how to code & decode a Boolean list to a String?
(Because I want people to share their boolean list with a string rather then a list of 90 1 and 0s.)
EDIT: got it working now! ty all for helping
string text = new string(tmpboolist.Select(x => x ? '1' : '0').ToArray());
byte[] bytes = getBitwiseByteArray(text); //http://stackoverflow.com/a/6756231/1184013
String Arraycode = Convert.ToBase64String(bytes);
System.Windows.MessageBox.Show(Arraycode);
//first it makes a string out of the boolean list then it uses the converter to make it an Byte[](array), then we use the base64 encoding to make the byte[] a String.(that can be decoded later)
I ll look into the encoding32 later, ty for all the help again :)
You should store your boolean values in a BitArray.
var values = new BitArray(92);
values[0] = false;
values[1] = true;
values[2] = true;
...
Then you can convert the BitArray to a byte array
var bytes = new byte[(values.Length + 7) / 8];
values.CopyTo(bytes);
and the byte array to a Base64 string
var result = Convert.ToBase64String(bytes);
Reversely, you can convert a Base64 string to a byte array
var bytes2 = Convert.FromBase64String(result);
and the byte array to a BitArray
var values2 = new BitArray(bytes2);
The Base64 string looks like this: "Liwd7bRv6TMY2cNE". This is probably a bit unhandy for sharing between people; have a look at human-oriented base-32 encoding:
Anticipated uses of these [base-32 strings] include cut-
and-paste, text editing (e.g. in HTML files), manual transcription via a
keyboard, manual transcription via pen-and-paper, vocal transcription over
phone or radio, etc.
The desiderata for such an encoding are:
minimizing transcription errors -- e.g. the well-known problem of confusing
'0' with 'O'
embedding into other structures -- e.g. search engines, structured or
marked-up text, file systems, command shells
brevity -- Shorter [strings] are better than longer ones.
ergonomics -- Human users (especially non-technical ones) should find the
[strings] as easy and pleasant as possible. The uglier the [strings] looks, the worse.
To start with, it's a bad idea to concatenate strings in a loop like that - at least use StringBuilder, or use something like this with LINQ:
string text = new string(tmpboolist.Select(x => x ? '1' : '0').ToArray());
But converting your string to a List<bool> is easy with LINQ, using the fact that string implements IEnumerable<char>:
List<bool> values = text.Select(c => c == '1').ToList();
It's not clear where the byte array comes in... but you should not try to represent arbitrary binary data in a string just using Encoding.GetString. That's not what it's for.
If you don't care what format your string uses, then using Base64 will work well - but be aware that if you're grouping your Boolean values into bytes, you'll need extra information if you need to distinguish between "7 values" and "8 values, the first of which is False" for example.
Since I am infering from your code you want a string with n digits of either 1 or 0 depending onthe internal lists bool value then how about...
public override string ToString()
{
StringBuilder output = new StringBuilder(91);
foreach(bool item in this.tempboolist)
{
output.Append(item ? "1" : "0");
}
return output.ToString();
}
Warning this was off the cuff typing, I have not validated this with a compiler yet!
This function does what you want:
public String convertBArrayToStr(bool[] input)
{
if (input == null)
return "";
int length = input.Count();
int byteArrayCount = (input.Count() - 1) / 8 + 1;
var bytes = new char[byteArrayCount];
for (int i = 0; i < length; i++ )
{
var mappedIndex = (i - 1) / 8;
bytes[mappedIndex] = (char)(2 * bytes[mappedIndex] +(input[i] == true ? 1 : 0));
}
return new string(bytes);
}
I need to take an int and turn it into its byte form.
i.e. I need to take '1' and turn it into '00000001'
or '160' and turn it into '10100000'
Currently, I am using this
int x = 3;
string s = Convert.ToString(x, 2);
int b = int.Parse(s);
This is an awful way to do things, so I am looking for a better way.
Any Suggestions?
EDIT
Basically, I need to get a list of every number up to 256 in base-2. I'm going to store all the numbers in a list, and keep them in a table on my db.
UPDATE
I decided to keep the base-2 number as a string instead of parsing it back. Thanks for the help and sorry for the confusion!
If you need the byte form you should take a look at the BitConverter.GetBytes() method. It does not return a string, but an array of bytes.
The int is already a binary number. What exactly are you looking to do with the new integer? What you are doing is setting a base 10 number to a base 2 value. That's kind of confusing and I think you must be trying to do something that should happen a different way.
I don't know what you need at the end ... this may help:
Turn the int into an int array:
byte[] bytes = BitConverter.GetBytes(x);
Turn the int into a bit array:
BitArray bitArray = new BitArray(new[] {x});
You can use BitArray.
The code looks a bit clumsy, but that could be improved a bit.
int testValue = 160;
System.Collections.BitArray bitarray = new System.Collections.BitArray(new int[] { testValue });
var bitList = new List<bool>();
foreach (bool bit in bitarray)
bitList.Add(bit);
bitList.Reverse();
var base2 = 0;
foreach (bool bit in bitList)
{
base2 *= 10; // Shift one step left
if (bit)
base2++; // Add 1 last
}
Console.WriteLine(base2);
I think you are confusing the data type Integer with its textual representation.
int x = 3;
is the number three regardless of the representation (binary, decimal, hexadecimal, etc.)
When you parse the binary textual representation of an integer back to integer you are getting a different number. The framework assumes you are parsing the number represented in the decimal base and gives the corresponding integer.
You can try
int x = 1600;
string s = Convert.ToString(x, 2);
int b = int.Parse(s);
and it will throw an exception because the binary representation of 1600 interpreted as decimal
is too big to fit in an integer