As per title, can someone post some code to convert an integer to a long?
Regards
As per title, can someone post some code to convert an integer to a long?
Regards
Your subject sounds like you want to perform some kind of operation on two integers, with a long result. The content of your post sounds like you want to convert a single integer to a single long.
Can you tell us, specifically, what you really want to do?
I have a lsb and a msb part of a 32bit bit variable, therefore two 16bit ints.
I want to combine them back into a single 32bit variable
how about
long result;
int high;
int low;
high = 0x1234;
low = 0xabcd;
result = (high << 16) + low;
Well that will fail. The default integer size is 16 bits on the Arduino so
any shift-left-by-16 on an int is going to return 0.
copy the high int to the long result, shift the long left by 16, or in the low part...
great catch. That probably explains why some of my prior bit manipulation didn't work.
result = high;
result = result << 16;
result += low;
Yes, needs to be casted.
Im trying this but the damm thing cuts anything over 16bit wide.
Just confirmed on AVR freaks the code is OK
uint32_t number = (((uint32_t)(odo_ms<<16)) + (odo_ls));
Serial.print((uint32_t)number);
what on earth?????
This works. It casts the first argument which is mentioned below by MarkT,
void setup() {
Serial.begin(9600);
unsigned int LSB = 0x00ff;
unsigned int MSB = 0xff00;
unsigned long Result;
Result = (unsigned long)MSB << 16 | LSB;
Serial.println(Result,HEX);
}
void loop() {}
casemod:
Yes, needs to be casted.Im trying this but the damm thing cuts anything over 16bit wide.
Just confirmed on AVR freaks the code is OKuint32_t number = (((uint32_t)(odo_ms<<16)) + (odo_ls));
Serial.print((uint32_t)number);
what on earth?????
Because the expression "odo_ms << 16" is int and thus a 16 bit shift is used.
You need to cast odo_ms itself.
MarkT:
casemod:
Yes, needs to be casted.Im trying this but the damm thing cuts anything over 16bit wide.
Just confirmed on AVR freaks the code is OKuint32_t number = (((uint32_t)(odo_ms<<16)) + (odo_ls));
Serial.print((uint32_t)number);
what on earth?????Because the expression "odo_ms << 16" is int and thus a 16 bit shift is used.
You need to cast odo_ms itself.
AHA $)
Of course, create a temp uint32_t var and shift that.
uint32_t MSB = odo_ms;
uint32_t number = ((MSB<<16) + (odo_ls));
Or, in your original code, move the cast:
uint32_t number = ((((uint32_t)odo_ms<<16)) + (odo_ls));
There are way more parentheses in that statement than are needed.
uint32_t number = ((uint32_t)odo_ms<<16) + odo_ls;