2015/11/03

Convert Millisecond (Decimal Fraction) to 32-bits Binary Using Arduino

The function millis2bin() can be used to convert millisecond to Network Time Protocol (NTP) timestamp fraction (32-bits unsigned long) used by both NTP servers and clients.

Code

/*
  Program for convert millisecond (decimal fraction) to 32-bits binary 
  By Befun Hung on Nov. 2, 2015
 */

void setup() {   
  
  Serial.begin(115200);
  
  int i;
  unsigned long tempval=1;
  for (i=0;i<32;i++) {
    Serial.print(i);
    Serial.print(" ");
    Serial.print(tempval << (31-i));
    Serial.print(" ");
    tempval = 1;
    Serial.println(tempval << (31-i),BIN);
  }
  for (i=0;i<1000;i++) {
    Serial.print(i);
    Serial.print(" ");
    Serial.println(millis2bin((float) i/1000),BIN);
    // millis2bin((float) i/1000);
  }
}

unsigned long millis2bin( float fraction) {
  int j=0;
  unsigned long return_value = 0;
  unsigned long one = 1;
  
  while (fraction != 0 && j < 32) {
    fraction = fraction * 2.0;
    if (fraction >= 1.0) {
      return_value = return_value | (one << (31 - j));
      fraction = fraction -1;
    }
    j++;
  }
  // Serial.print(return_value);
  // Serial.print(" ");
  // Serial.println(return_value,BIN);
  return return_value;
}

// the loop routine runs over and over again forever:
void loop() {
}

Serial Monitor Output