I am a little surprised by the output of the following code:
double array[] = {4, 5, 6, 8, 10, 20};
double* p = array + 3;
//Print array address
cout << (unsigned long)(array) << endl; //This prints 1768104
cout << (unsigned long)(p) << endl; //This prints 1768128
//print p - array
cout << (unsigned long)(p - array) << endl; // This prints 3
I am surprised that the last line prints 3. Shouldn't it print 24 = 3 * 8 bytes? Also, as expected,
the address of p is the address of array + 3 * 8 bytes. This seems inconsistent.
In fact, it is not even a legal assignment to write:
p = p - array; // can't assign an int to type double* No idea, why this is an int.
Pointer arithmetic works in multiples of the size being operated on. p is 3 double sizes greater than array, so that's why you get that response. It's the same reason your p = array + 3 line worked.
If you want the 24, do your casting differently to operate on byte-sized values:
cout << (char *)p - (char *)array;
Your statement p = p - array is meaningless - you can't assign an integer (the difference between pointers) to a pointer variable.
This is how pointer arithmetic works.
You may try like this:-
cout << (char *)p - (char *)array;
Related
One of my OpenCL helper functions writing to global memory in one place runs just fine, and the kernel executes typically. Still, when run from directly after that line, it freezes/crashes the kernel, and my program can't function.
The values in this function change (different values for an NDRange of 2^16), and therefore the loops change as well, and not all threads can execute the same code because of the conditionals.
Why exactly is this an issue? Am I missing some kind of memory blocking or something?
void add_world_seeds(yada yada yada...., const uint global_id, __global long* world_seeds)
for (; indexer < (1 << 16); indexer += increment) {
long k = (indexer << 16) + c;
long target2 = (k ^ e) >> 16;
long second_addend = get_partial_addend(k, x, z) & MASK_16;
if (ctz(target2 - second_addend) < mult_trailing_zeroes) { continue; }
long a = (((first_mult_inv * (target2 - second_addend)) >> mult_trailing_zeroes) ^ (J1_MUL >> 32)) & mask;
for (; a < (1 << 16); a += increment) {
world_seeds[global_id] = (a << 32) + k; //WORKS HERE
if (get_population_seed((a << 32) + k, x, z) != population_seed_state) { continue; }
world_seeds[global_id] = (a << 32) + k; //DOES NOT WORK HERE
}
}
for (; a < (1 << 16); a += increment) {
world_seeds[global_id] = (a << 32) + k; //WORKS HERE
if (get_population_seed((a << 32) + k, x, z) != population_seed_state) { continue; }
world_seeds[global_id] = (a << 32) + k; //DOES NOT WORK HERE
}
There was in fact a bug causing the undefined behavior in the code, in particular the main reversal kernel included a variable in the arguments called "increment", and in that same kernel I defined another variable called increment. It compiled fine but led to completely all over the wall wrong results and memory crashes.
I am looking for a good way to round an int in Qt to the nearest 5.
e.g:
8 -> 10
12 -> 10
13 -> 15
15 -> 15
17 -> 15
and so on
Rounding in C++ to the nearest integer number usually is done via:
static_cast<int>(number + 0.5);
Now, to round it to the next 5, I would bring it into the system where we can apply this rounding rule (i.e. 5 -> 1, 6 -> 1.2) and then bring it back into the system where 5 really is 5:
int roundToNearestFive(int number)
{
return static_cast<int>(number / 5. + .5) * 5;
}
I find this formulation easiest.
Here a possible solution:
#include<iostream>
int toNearest5(int i) {
int r = i%5, o = 0;
if(r) {
o = r/5. >= .5 ? 5 : 0;
}
return (i-r+o);
}
int main() {
using namespace std;
cout << toNearest5(8) << endl;
cout << toNearest5(12) << endl;
cout << toNearest5(13) << endl;
cout << toNearest5(15) << endl;
cout << toNearest5(17) << endl;
}
The idea is to get the number and round it to the lowest multiple of 5 (you can do that by removing the remainder), that is:
int remainder = i%5;
int rounded = i - remainder;
Now, you can check the remainder and add 5 to the rounded number if the remainder is greater than 2.5, otherwise add 0.
In order to check it, I've divided the remainder by 5 (its upper bound), so that to get a number in [0,1[ and check it with 0.5 to know how to round the original number.
It follows a more compact version of the same function:
int toNearest5(int i) {
int j = i%5;
return (i - j + (j/5. >= .5 ? 5 : 0));
}
I don't know if the Qt framework offers something similar out of the box, but it's a matter of an one line function, you can easily write it for yourself.
I'm using the rainbowduino and it has some methods that take individual r g b values as unsigned chars, and some that take a 24bit rgb colour code.
I want to convert r g b values into this 24bit colour code of type uint32_t (so that all my code only has to use r g b values.
Any ideas?
I have already tried uint32_t result = r << 16 + g << 8 + b;
r = 100 g =200 b=0 gave green, but r=0 g=200 b=0 gave nothing
Rb.setPixelXY(unsigned char x, unsigned char y, unsigned char colorR, unsigned char colorG, unsigned char colorB)
This sets the pixel(x,y)by specifying each channel(color) with 8bit number.
Rb.setPixelXY(unsigned char x, unsigned char y, unit32_t colorRGB)
This sets the pixel(x,y)by specifying a 24bit RGB color code.
The drivers code is:
void Rainbowduino::setPixelXY(unsigned char x, unsigned char y, uint32_t colorRGB /*24-bit RGB Color*/)
{
if(x > 7 || y > 7)
{
// Do nothing.
// This check is used to avoid writing to out-of-bound pixels by graphics function.
// But this might slow down setting pixels (remove this check if fast disply is desired)
}
else
{
colorRGB = (colorRGB & 0x00FFFFFF);
frameBuffer[0][x][y]=(colorRGB & 0x0000FF); //channel Blue
colorRGB = (colorRGB >> 8);
frameBuffer[1][x][y]=(colorRGB & 0x0000FF); //channel Green
colorRGB = (colorRGB >> 8);
frameBuffer[2][x][y]=(colorRGB & 0x0000FF); //channel Red
}
}
So I would think similar to the above :
uint8_t x,y,r,b,g;
uint32_t result = (r << 16) | (g << 8) | b;
Rb.setPixelXY(x, y, result);
should work. It I think the above likely needs the parenthesis, to ensure proper ordering, as "+" is higher than "<<". Also likely won't hurt but the "|" is better, as not to prevent undesired carry's.
P.S. Remember when shifting to be unsigned, unless you want arithmetic shift versus logical.
and on that note I don't like shifts as they are often messed up and inefficient. Rather a union is simple and efficient.
union rgb {
uint32_t word;
uint8_t byte[3];
struct {
uint8_t blue;
uint8_t green;
uint8_t red;
} color ;
}rgb ;
// one way to assign by discrete names.
rbg.color.blue = b;
rbg.color.green = g;
rbg.color.red = r;
//or assign using array
rgb.byte[0] = b;
rgb.byte[1] = g;
rgb.byte[2] = r;
// then interchangeably use the whole integer word when desired.
Rb.setPixelXY(x, y, rgb.word);
no messing with keeping track of shifts.
One way to approach this would be to shift the bits to the left...
uint32_t result = r << 16 + g << 8 + b;
I'm very interested in cryptography, and since I like programming too, I decided to make a little program to encrypt files using XTEA encryption algorithm.
I got inspired from Wikipedia, and so I wrote this function to do the encryption (To save space, I won't post the deciphering function, as it is almost the same):
void encipher(long *v, long *k)
{
long v0 = v[0], v1 = v[1];
long sum = 0;
long delta = 0x9e3779b9;
short rounds = 32;
for(uint32 i = 0; i<rounds; i++)
{
v0 += (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + k[sum & 3]);
sum += delta;
v1 += (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + k[(sum>>11) & 3]);
}
v[0] = v1;
v[1] = v1;
}
Now when I want to use it, I wrote this code:
long data[2]; // v0 and v1, 64bits
data[0] = 1;
data[1] = 1;
long key[4]; // 4 * 4 bytes = 16bytes = 128bits
*key = 123; // sets the key
cout << "READ: \t\t" << data[0] << endl << "\t\t" << data[1] << endl;
encipher(data, key);
cout << "ENCIPHERED: \t" << data[0] << endl << "\t\t" << data[1] << endl;
decipher(data, key);
cout << "DECIPHERED: \t" << data[0] << endl << "\t\t" << data[1] << endl;
I always get either run-time crash or wrong decipher text:
I do understand the basics of the program, but I don't really know what is wrong with my code. Why is the enciphered data[0] and data1 the same? And why is deciphered data completely different from the starting data? Am I using the types wrong?
I hope you can help me solving my problem :) .
Jan
The problem is here:
v[0] = v1; // should be v[0] = v0
v[1] = v1;
Also, you only set the first 4 bytes of the key. The remaining 12 bytes are uninitialized.
Try something like this:
key[0] = 0x12345678;
key[1] = 0x90ABCDEF;
key[2] = 0xFEDCBA09;
key[3] = 0x87654321;
The fixed code gives me this output:
READ: 1
1
ENCIPHERED: -303182565
-1255815002
DECIPHERED: 1
1
For class, Im making a program that manages a hotel. Im getting a run-time error when my program gets to this function:Vector iterator not dereferencable. I used the debugger to find the problem area, but I cant figure out what is wrong with it. Any Suggestions?
Customer & ListOfCustomers::getByID(int id)
{
if(!sortedByID)sortByID();
vector<Customer>::iterator iter;
Customer cus;
cus.customerID=id;
iter = lower_bound(customers.begin(),customers.end(),cus,compareCustomersByID);
if( (*iter).customerID == id ) // <---DEBUGGER SAYS ERROR HERE IN THIS LINE
{
return *iter;
}
else
{
return NullCustomer();
}
}
Here is the lower_bound function. It is Inside #include algorithm
template<class _FwdIt,
class _Ty,
class _Pr> inline
_FwdIt lower_bound(_FwdIt _First, _FwdIt _Last,
const _Ty& _Val, _Pr _Pred)
{// find first element not before _Val, using _Pred
// _DEBUG_ORDER_PRED(_First, _Last, _Pred);
return (_Rechecked(_First,
_Lower_bound(_Unchecked(_First), _Unchecked(_Last), _Val, _Pred,
_Dist_type(_First))));
}
EDIT: added a space so that the lower_bound function would be formatted correctly as code.
You are using the lower_bound function for searching. Its purpose is a little different than that. This is what lower_bound does:
Returns an iterator pointing to the first element in the sorted range [first,last) which does not compare less than value.
And another definition from here:
Specifically, it returns the first position where value could be inserted without violating the ordering.
So for example, if the thing you are looking for is not in the vector, it will return an iterator that points after the last item in the vector, and that iterator can't be dereferenced because it does not exist.
Take a look at this example:
int myints[] = {10,20,30,30,20,10,10,20};
vector<int> v(myints,myints+8); // 10 20 30 30 20 10 10 20
vector<int>::iterator low;
sort (v.begin(), v.end()); // 10 10 10 20 20 20 30 30
low=lower_bound (v.begin(), v.end(), 60); // ^it will point here
cout << "lower_bound at position " << int(low- v.begin()) << endl;
As you can see from the output, the iterator will point to the 9th element in the vector (index 8). But the vector only has 8 elements (indexed 0-7). The explanation for this is that you can insert the new item in the vector at index 8 without violating the ordering.
I think that what you really want is the find function. Here is an example:
int myints[] = {10,20,30,30,20,10,10,20};
vector<int> v(myints,myints+8); // 10 20 30 30 20 10 10 20
vector<int>::iterator find_it1 = find(v.begin(), v.end(), 30);
vector<int>::iterator find_it2 = find(v.begin(), v.end(), 80);
if(find_it1 == v.end())
cout << "30 not found" << endl;
else
cout << "30 found at position " << int(find_it1 - v.begin()) << endl;
if(find_it2 == v.end())
cout << "80 not found" << endl;
else
cout << "80 found at position " << int(find_it2 - v.begin()) << endl;
Here is the output:
30 found at position 2
80 not found