Skip to content

Instantly share code, notes, and snippets.

@Aietes
Last active June 17, 2020 09:12
Show Gist options
  • Save Aietes/fb5b176fd1644b78b378076d9c4bdc8a to your computer and use it in GitHub Desktop.
Save Aietes/fb5b176fd1644b78b378076d9c4bdc8a to your computer and use it in GitHub Desktop.
Bit shifting in C
//print uint64_t 4 bits at a time, single HEX digit
uint64_t chipid = ESP.getEfuseMac();
for (size_t i = 0; i < 16; i++)
{
byte byte1 = chipid >> 4*i & 0x0000000F;
Serial.printf("%X ", byte1);
}
// 0 3 E A 4 A 0 4 A E 0 E 0 0 0 0
//print uint64_t 4 bits at a time, in pairs of 8 bits, single HEX digit
for (size_t i = 0; i < 8; i++)
{
byte byte1 = chipid >> (8*i)+4 & 0x0000000F;
byte byte2 = chipid >> 8*i & 0x0000000F;
Serial.printf("%X ", byte1);
Serial.printf("%X ", byte2);
}
// 3 0 A E A 4 4 0 E A E 0 0 0 0 0
//print uint64_t 8 bits at a time, HEX value
uint64_t chipid = ESP.getEfuseMac();
for (size_t i = 0; i < 8; i++)
{
byte byte1 = chipid >> 8*i & 0x000000FF;
Serial.printf("%02X ", byte1);
}
// 30 AE A4 40 EA E0 00 00
//printing directly into var
snprintf(chip_id, 12, "%04X%08X", (uint16_t)(chipid >> 32), (uint32_t)chipid);
//two bytes from byte array (byte 7 and 8) into integer variable
int key_addr
byte page[32];
for (size_t j = 0; j < 4; j++)
{
key_addr = ((page[j * 8 + 7] & 0xff) << 8) | (page[j * 8 + 6] & 0xff);
}
//integer variable to two bytes, reverse of above
int key_addr
byte byte1 = key_addr & 0x00ff;
byte byte2 = (key_addr & 0xff00) >> 8;
// print HEX encoded byte array
byte test_id[6] = {0xED, 0x4C, 0xBE, 0xC7, 0x0F, 0xDB};
for (size_t i = 0; i < 6; i++)
{
byte byte1 = test_id[i] >> 4 & 0x0F;
byte byte2 = test_id[i] & 0x0F;
Serial.printf("%X", byte1);
Serial.printf("%X ", byte2);
}
Serial.println();
//binary
for (size_t i = 0; i < 6; i++)
{
for (size_t j = 0; j < 8; j++)
{
byte bit = test_id[i] >> j & 1;
Serial.printf("%u", bit);
}
Serial.print(" ");
}
Serial.println();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment