Unknown time and date format - datetime

I'm using code that someone else wrote to load a file format that I can't find any docs or specs for. The file format is *.vpd which is the output of varioport readers used for EKG's.
It reads out 4 bytes for the time and 4 bytes for the date and are each stored in a 4 element array. In a test file I have, the 4 time bytes are { 19, 38, 3, 0 } and the 4 date bytes are { 38, 9, 8, 0 }. It could also be a 32-bit int, and the guy who wrote this is reading it wrong. Judging by the trailing 0 on both, I would assume little endian in which case the values of time and date as int32's are 206355 and 526630 respectively.
Do you know of any time/date formats that are expressed in 4 bytes (or a single int)? I'm hopelessly lost at the moment.
EDIT: I should add that I don't know what the values could be, apart from that the date is likely to be within the last few years.
The code, there are no comments associated with it.
s.Rstime = fread(fid, 4, 'uint8');
s.Rsdate = fread(fid, 4, 'uint8');

In the Varioport VPD file format, BCD (binary coded decimal) code is used for date and time. You had no chance to guess this, because the fread calls you posted are obviously nonsense. You are reading at the wrong places.
Try this in C/C++ (matlab code will look very similar):
typedef struct
{
int channelCount;
int scanRate;
unsigned char measureDate[3];
unsigned char measureTime[3];
...
}
VPD_FILEINFO;
...
unsigned char threeBytes[3];
size_t itemsRead = 0;
errno_t err = _tfopen_s(&fp, filename, _T("r+b"));
// n.b.: vpd files have big-endian byte order!
if (err != 0)
{
_tprintf(_T("Cannot open file %s\n"), filename);
return false;
}
// read date of measurement
fseek(fp, 16, SEEK_SET);
itemsRead = fread(&threeBytes, 1, 3, fp);
if (itemsRead != 3)
{
_tprintf(_T("Error trying to read measureDate\n"));
return false;
}
else
{
info.measureDate[0] = threeBytes[0]; // day, binary coded decimal
info.measureDate[1] = threeBytes[1]; // month, binary coded decimal
info.measureDate[2] = threeBytes[2]; // year, binary coded decimal
}
// read time of measurement
fseek(fp, 12, SEEK_SET);
itemsRead = fread(&threeBytes, 1, 3, fp);
if (itemsRead != 3)
{
_tprintf(_T("Error trying to read measureTime\n"));
return false;
}
else
{
info.measureTime[0] = threeBytes[0]; // hours, binary coded decimal
info.measureTime[1] = threeBytes[1]; // minutes, binary coded decimal
info.measureTime[2] = threeBytes[2]; // seconds, binary coded decimal
}
...
_tprintf(_T("Measure date == %x %x %x\n"),
info.measureDate[0],
info.measureDate[1],
info.measureDate[2]);
_tprintf(_T("Measure time == %x %x %x\n"),
info.measureTime[0],
info.measureTime[1],
info.measureTime[2]);

It's not important anymore, I doubt anyone would be able to answer it anyway.

Related

Converting ASCII to int in Arduino

I am trying to get user input from the serial monitor to turn a stepper motor according to the input. However my code returns the ASCII value rather than the original input.
#include <Stepper.h>
Stepper small_stepper(steps_per_motor_revolution, 8, 10, 9, 11);
void setup() {
// Put your setup code here, to run once:
Serial.begin(9600);
Serial.println("Ready");
}
void loop() {
// Put your main code here, to run repeatedly:
int Steps2Take = Serial.read();
Serial.println(Steps2Take); // Printing
if (Steps2Take == -1)
Steps2Take = 0;
else {
small_stepper.setSpeed(1000); // Setting speed
if (Steps2Take > 0)
small_stepper.step(Steps2Take * 32);
else
small_stepper.step(-Steps2Take * 32);
delay(2);
}
}
Just use the .toInt() function.
You should read the string from your serial and after that convert it to integer.
Serial.print(Serial.readString().toInt());
You could do this three ways! Notice, if the number is greater than 65535 then you have to use a long variable. With decimals use float variable.
You can use the toInt(), or toFloat() which require a String type variable. Heads up as the toFloat() is very time consuming.
// CODE:
String _int = "00254";
String _float = "002.54";
int value1 = _int.toInt();
float value2 = _float.toFloat();
Serial.println(value1);
Serial.println(value2);
// OUTPUT:
254
2.54
You could use the atoi. The function accepts a character array and then converts it to an integer.
// CODE:
// For some reason you have to have +1 your final size; if you don't you will get zeros.
char output[5] = {'1', '.', '2', '3'};
int value1 = atoi(output);
float value2 = atof(output);
Serial.print(value1);
Serial.print(value2);
// OUTPUT:
1
1.23
If you had a Character Array and and wanted to convert it to a string because you didn't know the length...like a message buffer or something, I dunno. You could use this below to change it to a string and then implement the toInt() or toFloat().
// CODE:
char _int[8];
String data = "";
for(int i = 0; i < 8; i++){
data += (char)_int[i];
}
char buf[data.length()+1];
data.toCharArray(buf, data.length()+1);
If it is just a "type-conversion" problem, you can use something like this:
int a_as_int = (int)'a';
or
#include <stdlib.h>
int num = atoi("23"); //atoi = ascii to integer
as it was point out here.
Does it solve the problem?

Difference normal cast and pointer cast

i've written a following code:
void union_bytes() {
float fnum = 1209.1996f;
union endian {
float fnum;
int inum;
unsigned char cnum[4];
}instance;
instance.fnum = fnum;
printf("Number = %f\nLittle Endian = %.2x %.2x %.2x %.2x\nHex = %x\n", instance.fnum, instance.cnum[0],
instance.cnum[1], instance.cnum[2], instance.cnum[3], instance.inum);
}
void pointer_bytes() {
float fnum = 1209.1996f;
int *ptr_inum = (int*)&fnum;;
unsigned char *cbytes = (unsigned char *)&fnum;
printf("Number = %f\nLittle Endian = %.2x %.2x %.2x %.2x\nHex = %x\n", fnum, cbytes[0], cbytes[1], cbytes[2], cbytes[3], *ptr_inum);
}
and i want to know, why i have to do such things : int *ptr_inum = (int*)&fnum; in order to get little-endian, and i cant do so like this:
int inum = (int)fnum;
i suppose, the last option forces fnum to lose some bytes, but i still dont know how such numbers are represent in memory(and which bytes are exactly to lose).
Why in this case:
unsigned char ch[4] = { 0x3b, 0x51, 0x7a, 0x24 };
float f = *(float*)ch;
When comes to casting, ch doesnt give the first nible 0x3b which is then a float, rather than it converts all the bytes in table compounding the entire float.
Thanks
why i have to do such things : int ptr_inum = (int)&fnum; in order
to get little-endian, and i cant do so like this: int inum =
(int)fnum;
There is some terminology confusion here. Little-endian is a specific order of bytes for multi-byte structures, and is usually mentioned as opposed to big-endian.
What you are getting is as a result of execution of the first statement is:
make the variable that points to integer point to a location where a floating-point number is stored, so that later its word representation can be retrieved/modifed int by int. Say, for number 1.9 in IEEE-754 compliant implementations is represented as 0x3ff33333, so on little-endian architectures if your int is 32bit you would get 0x3ff33333.
Second statement would mean: give me an integer variable, that results from a float pointing number. By standard, that means dropping of the decimal, so out of 1.9 you will get 1.

Sum calculation error in Arduino Mega 2560

I am using Arduino Mega 2560 to communicate with the server.
I create a byte array, uses the first digit as a indicator (to tell the server this message is from a arduino device) and the last digit for check sum.
// for creating msg
void createmsg(){
int index = 0;
memset(MSGpack,0,sizeof(MSGpack));
byte sum;
MSGpack[0] = 0x23; // for identifing it is arduino
// for current readings
index = 14;
for (int i = 0; i < 7; i++){
float voltage = readcurrent(i);
injectByte(voltage, index);
index = index + 4;
}
////////////////////////////////////////////////////////////DATE
myRTC.updateTime();
index = 162;
int timeVAR = myRTC.dayofmonth;//reporting day
injectByte(timeVAR, index);
timeVAR = myRTC.month;
injectByte(timeVAR, 166); //reporting month
timeVAR = myRTC.year;
injectByte(timeVAR, 170); //reporting year
timeVAR = myRTC.year + myRTC.month + myRTC.dayofmonth; //sum of date
injectByte(timeVAR, 158);
////////////////////////////////////////////////////////////DATE
////////////////////////////////////////////////////////////TIME
myRTC.updateTime();
timeVAR = myRTC.hours;
injectByte(timeVAR, 146); //reporting hour
timeVAR = myRTC.minutes;
injectByte(timeVAR, 150); //reporting second
timeVAR = myRTC.hours + myRTC.minutes;
injectByte(timeVAR, 154); //sum of time
////////////////////////////////////////////////////////////TIME
//to pass buffer verification
for (int i = 0; i < 186; i++) {
sum += MSGpack[i];
}
MSGpack[186] = sum;
}
void injectByte(float value, int index){
byte * b = (byte *) &value;
MSGpack[index] = b[3];
MSGpack[index + 1] = b[2];
MSGpack[index + 2] = b[1];
MSGpack[index + 3] = b[0];
}
At the server side, it checks if the last digit equals to the sum of all the previous digit, if yes, it identify the received package is valid.
The problems is, if I comment out the date and time data, the server could identify the package as valid. But if I add the data back into the package, the server says the package is not valid.
So I conclude it is check sum error at the Arduino side.
According to here, "some constant calculations may overflow" && "Know at what point your variable will "roll over" " etc at "Programming tips:"
A byte stores an 8-bit unsigned number, from 0 to 255. So what if the check sum calculated is larger than 255? What will be resulted?
And how should I solve this issue and let the server receive a valid package? Thanks!
I would suggest changing your byte array to being an unsigned byte array
then change sum to an unsigned int or unsigned short (16 bits will suffice)
Where you calculate the sum:
sum = (sum + MSGpack[i]) & 0xFF;
MSGpack[186] = (unsigned byte)sum;
I think the issue is that you are adding signed numbers together and also not limiting the output to 8 bits. As you are using the bytes as unsigned, it's best to tell the compiler explicitly so it doesn't make rash assumptions.

Codility K-Sparse Test **Spoilers**

Have you tried the latest Codility test?
I felt like there was an error in the definition of what a K-Sparse number is that left me confused and I wasn't sure what the right way to proceed was. So it starts out by defining a K-Sparse Number:
In the binary number "100100010000" there are at least two 0s between
any two consecutive 1s. In the binary number "100010000100010" there
are at least three 0s between any two consecutive 1s. A positive
integer N is called K-sparse if there are at least K 0s between any
two consecutive 1s in its binary representation. (My emphasis)
So the first number you see, 100100010000 is 2-sparse and the second one, 100010000100010, is 3-sparse. Pretty simple, but then it gets down into the algorithm:
Write a function:
class Solution { public int sparse_binary_count(String S,String T,int K); }
that, given:
string S containing a binary representation of some positive integer A,
string T containing a binary representation of some positive integer B,
a positive integer K.
returns the number of K-sparse integers within the range [A..B] (both
ends included)
and then states this test case:
For example, given S = "101" (A = 5), T = "1111" (B=15) and K=2, the
function should return 2, because there are just two 2-sparse integers
in the range [5..15], namely "1000" (i.e. 8) and "1001" (i.e. 9).
Basically it is saying that 8, or 1000 in base 2, is a 2-sparse number, even though it does not have two consecutive ones in its binary representation. What gives? Am I missing something here?
Tried solving that one. The assumption that the problem makes about binary representations of "power of two" numbers being K sparse by default is somewhat confusing and contrary.
What I understood was 8-->1000 is 2 power 3 so 8 is 3 sparse. 16-->10000 2 power 4 , and hence 4 sparse.
Even we assume it as true , and if you are interested in below is my solution code(C) for this problem. Doesn't handle some cases correctly, where there are powers of two numbers involved in between the two input numbers, trying to see if i can fix that:
int sparse_binary_count (const string &S,const string &T,int K)
{
char buf[50];
char *str1,*tptr,*Sstr,*Tstr;
int i,len1,len2,cnt=0;
long int num1,num2;
char *pend,*ch;
Sstr = (char *)S.c_str();
Tstr = (char *)T.c_str();
str1 = (char *)malloc(300001);
tptr = str1;
num1 = strtol(Sstr,&pend,2);
num2 = strtol(Tstr,&pend,2);
for(i=0;i<K;i++)
{
buf[i] = '0';
}
buf[i] = '\0';
for(i=num1;i<=num2;i++)
{
str1 = tptr;
if( (i & (i-1))==0)
{
if(i >= (pow((float)2,(float)K)))
{
cnt++;
continue;
}
}
str1 = myitoa(i,str1,2);
ch = strstr(str1,buf);
if(ch == NULL)
continue;
else
{
if((i % 2) != 0)
cnt++;
}
}
return cnt;
}
char* myitoa(int val, char *buf, int base){
int i = 299999;
int cnt=0;
for(; val && i ; --i, val /= base)
{
buf[i] = "0123456789abcdef"[val % base];
cnt++;
}
buf[i+cnt+1] = '\0';
return &buf[i+1];
}
There was an information within the test details, showing this specific case. According to this information, any power of 2 is considered K-sparse for any K.
You can solve this simply by binary operations on integers. You are even able to tell, that you will find no K-sparse integers bigger than some specific integer and lower than (or equal to) integer represented by T.
As far as I can see, you must pay also a lot of attention to the performance, as there are sometimes hundreds of milions of integers to be checked.
My own solution, written in Python, working very efficiently even on large ranges of integers and being successfully tested for many inputs, has failed. The results were not very descriptive, saying it does not work as required within question (although it meets all the requirements in my opinion).
/////////////////////////////////////
solutions with bitwise operators:
no of bits per int = 32 on 32 bit system,check for pattern (for K=2,
like 1001, 1000) in each shift and increment the count, repeat this
for all numbers in range.
///////////////////////////////////////////////////////
int KsparseNumbers(int a, int b, int s) {
int nbits = sizeof(int)*8;
int slen = 0;
int lslen = pow(2, s);
int scount = 0;
int i = 0;
for (; i < s; ++i) {
slen += pow(2, i);
}
printf("\n slen = %d\n", slen);
for(; a <= b; ++a) {
int num = a;
for(i = 0 ; i < nbits-2; ++i) {
if ( (num & slen) == 0 && (num & lslen) ) {
scount++;
printf("\n Scount = %d\n", scount);
break;
}
num >>=1;
}
}
return scount;
}
int main() {
printf("\n No of 2-sparse numbers between 5 and 15 = %d\n", KsparseNumbers(5, 15, 2));
}

Confused over some date/time calculations

So, I am trying to calculate the time between two dates that fits certain criteria (here: work / non-work) and I'm confused about the results as I can't find out why it's wrong.
But first, some code;
**Input Date A:** 2009-01-01 2:00 pm
**Input Date B:** 2009-01-02 9:00 am
So, as you can see, the total timespan (calculated e.g. by DateB.Substract(DateA)) is 19 hours.
I now want to calculate how many hours in this timespan are "non-work" hours, based on an average work day from 8am to 5pm - Result should be 15 hours (So, 19 - 15 = 4 hours total work time) (2:00 pm to 5:00 pm plus 8:00 am to 9:00 am)
But, following my code
DateTime _Temp = new DateTime(2009, 1, 1, 14, 0, 0);
DateTime _End = new DateTime(2009, 1, 2, 9, 0, 0);
int _WorkDayStart = 8;
int _WorkDayEnd = 17;
int _Return = 0;
while (_End > _Temp)
{
if (_Temp.Hour <= _WorkDayStart || _Temp.Hour >= _WorkDayEnd)
_Return++;
_Temp = _Temp.AddHours(1);
}
the result is 16 hours (19 - 16 = 3 hours total work time) - I don't see where the mistake is, so there is one hour missing?! I refactored it on paper and it should work as intended... but doesn't :-/
Anyone sees the mistake?
You're counting both ends as non-work, instead of just one. This line:
if (_Temp.Hour <= _WorkDayStart || _Temp.Hour >= _WorkDayEnd)
should probably be:
if (_Temp.Hour < _WorkDayStart || _Temp.Hour >= _WorkDayEnd)
You're effectively stepping through "start hours". So 8am itself should count as a work hour, because it's the start of a work hour, but 5pm won't because it's the start of a non-work hour.
I would also strongly advise you to either put braces around the body of the if statement or at least indent the following line. (I'd further advise you to use camelCase for local variables, but that's just a convention thing - I've never seen C# code written with that convention for local variables before now. You may want to read Microsoft's naming conventions document - it doesn't specify local variables, but they;re generally in camel case.)
Finally, I personally find it easier to read conditions where the "thing that's changing" is on the left - so I'd change your loop condition to:
while (_Temp < _End)
An alternative is to change it into a for loop. With all of these changes, the code would be:
DateTime start = new DateTime(2009, 1, 1, 14, 0, 0);
DateTime end = new DateTime(2009, 1, 2, 9, 0, 0);
int workDayStart = 8;
int workDayEnd = 17;
int nonWorkHours = 0;
for (DateTime time = start; time < end; time = time.AddHours(1))
{
if (time.Hour < workDayStart || time.Hour >= workDayEnd)
{
nonWorkHours++;
}
}
Finally, extract this into a method:
public static int CountNonWorkHours(DateTime start, DateTime end,
int workDayStart, int workDayEnd)
{
int nonWorkHours = 0;
for (DateTime time = start; time < end; time = time.AddHours(1))
{
if (time.Hour < workDayStart || time.Hour >= workDayEnd)
{
nonWorkHours++;
}
}
return nonWorkHours;
}
EDIT: Regarding konamiman's suggestion... yes, looping over each hour is very inefficient. However, it's relatively easy to get right. Unless you're going to be doing this a lot with long time periods, I'd use this fairly simple code. It would be very easy to end up with off-by-one errors in various situations if you tried to do a per-day version. While I don't like inefficient code, I don't mind it if it's not hurting me :)
If you plan to reuse this code, I would refactor it to avoid the loop. You could just multiply the number of whole days by the labour hours per day, then treat the first and the last day of the interval as special cases.
You could also use this to avoid a loop
DateTime startDate = new DateTime(2009, 1, 1, 14, 0, 0);
DateTime endDate = new DateTime(2009, 1, 2, 9, 0, 0);
int startTime = 8;
int endTime = 17;
int ret = ((endDate.Subtract(startDate).Days - 1) * 8)
+ (startDate.Hour >= startTime && startDate.Hour < endTime ? endTime - startDate.Hour : 0)
+ (endDate.Hour > startTime && endDate.Hour <= endTime ? endDate.Hour - startTime : 0);

Resources