Попробуйте это консольное приложение:
static void Main(string[] args)
{
//Encoding _UTF8 = Encoding.UTF8;
string[] _mainString = { "Héllo World" };
Console.WriteLine("Main String: " + _mainString);
//Convert a string to utf-8 bytes.
byte[] _utf8Bytes = Encoding.UTF8.GetBytes(_mainString[0]);
//Convert utf-8 bytes to a string.
string _stringuUnicode = Encoding.UTF8.GetString(_utf8Bytes);
Console.WriteLine("String Unicode: " + _stringuUnicode);
}
Мне нравится использовать arc4random ()
, потому что это не требует, чтобы вы запускали генератор случайных чисел. Он также удобно возвращает uint_32_t, поэтому вам не нужно беспокоиться о том, что результат будет между 0 и 1 и т. Д. Он просто выдаст вам случайное целое число.
int myRandom() {
return (arc4random() % 2 ? 1 : -1);
}
If I understand the question correctly, you want a pseudorandom sequence of 1 and -1:
int f(void)
{
return random() & 1 ? 1 : -1;
// or...
// return 2 * (random() & 1) - 1;
// or...
// return ((random() & 1) << 1) - 1;
// or...
// return (random() & 2) - 1; // This one from Chris Lutz
}
Update: Ok, something has been bothering me since I wrote this. One of the frequent weaknesses of common RNGs is that the low order bits can go through short cycles. It's probably best to test a higher-order bit: random() & 0x80000 ? 1 : -1
To generate either 1 or -1 directly, you could do:
int PlusOrMinusOne() {
return (rand() % 2) * 2 - 1
}
But why are you worried about the broader range?
This extra step won't give you any additional "randomness". Just generate your number straight away in the range that you need (e.g. -10..10). Standard rand() will return a value from this range: 0..1 You can multiply it by a constant to increase the span of the range or you can add a constant to push it left/right on the X-Axis. E.g. to generate random values from from (-5..10) range you will have: rand()*15-5
rand
даст вам число от 0 до RAND_MAX, которое будет охватывать каждый бит в int
, за исключением знака. Сдвигая этот результат влево на 1 бит, вы превращаете MSB со знаком в знак, но обнуляете 0 th бит, который можно повторно заполнить случайным битом из другого вызова rand
. Код будет выглядеть примерно так:
int my_rand()
{
return (rand() << 1) + (rand() & 1);
}