printf格式化输出几点注记

本文分享了作者多年C/C++编程经验中的几个实用技巧,包括如何表达文件大小、打印size_t和time_t类型的变量、使用OpenSSL进行HMAC-SHA1加密等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

搞了很多年c/c++,有很多细小的东西,曾经不止一次遇到,可是一直都是放在零散的地方,要用的时候怎么也找不到,今天,我痛下决心,改掉不良习惯,把这些经验或是tips记录在这里,便于日后查找。

1.在统计网络下载信息时,如何表达文件大小?


下面是输出结果


2.打印size_t类型数据的长度,使用%lu。

下面是一个使用OpenSSL中HMAC-Sha1算法计算加密字符串的例子,记录如下。

//gcc -g hmac_sha1_demo1.c -o hmac_sha1_demo1 -lcrypto --std=c99

#include <stdio.h>
#include <string.h>
#include <openssl/hmac.h>

int main()
{
    // The key to hash
    char key[] = "012345678";

    // The data that we're going to hash using HMAC
    char data[] = "hello world";

    unsigned char* digest;

    // Using sha1 hash engine here.
    // You may use other hash engines. e.g EVP_md5(), EVP_sha224, EVP_sha512, etc
    digest = HMAC(EVP_sha1(), key, strlen(key), (unsigned char*)data, strlen(data), NULL, NULL);
    printf("%s, len %lu\n", digest, strlen(digest));

    // Be careful of the length of string with the choosen hash engine. SHA1 produces a 20-byte hash value which rendered as 40 characters.
    // Change the length accordingly with your choosen hash engine
    char mdString[41] = {'\0'};
    for(int i = 0; i < 20; i++)
         sprintf(&mdString[i*2], "%02x", (unsigned int)digest[i]);

    printf("HMAC digest: %s\n", mdString);

    return 0;
}
运行结果



3.打印time_t类型的数据,使用%lu,参见下面的小例子:时间字符串转换为时间戳

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

time_t str2time(const char* s){
    struct tm tm_time;
    strptime(s, "%Y%m%d%H%M%S", &tm_time);
    time_t p = mktime(&tm_time);
    return p;
}


int main(int argc, char* argv[]){
    const char* str = "20150622193125";
    time_t timep;
    timep = str2time(str);
    printf("%lu\n", timep);

    time(&timep);
    printf("%lu\n", timep);
    return 0;
}
下面是运行结果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值