Reputation: 13195
I am getting the following error:
warning: conversion to ‘short unsigned int’ from ‘int’ may alter its value [-Wconversion]
for the method
template<typename T> bool get_int(FILE* IN, T* val) {
T rc = 0;
for (size_t i = 0; i < sizeof(T) << 3; i += 8) {
int temp = getc(IN);
if (temp == EOF)
return false;
rc |= (T)temp << i;
}
*val = rc;
return true;
}
when I have the lines
unsigned short foo;
get_int<unsigned short>(IN, &foo);
How can I get rid of this GCC warning?
Upvotes: 0
Views: 250
Reputation: 1226
Try this:
rc |= (T)(temp << i);
(T)temp
is promoted to int again for the bitwise shift.
Upvotes: 1
Reputation: 302987
Don't reinvent the wheel. There's already a function to read multiple bytes of binary data: fread()
:
template<typename T>
bool get_int(FILE* f, T* val) {
return fread(val, sizeof(T), 1, f) == sizeof(T);
}
Note that you don't have to explicitly specify the types when calling function templates - you can let deduction to its thing:
unsigned short foo;
get_int(IN, &foo);
Upvotes: 1