首页 > 编程语言 >C++数据格式化5 - uint转换成十六进制字符串&二进制的data打印成十六进制字符串

C++数据格式化5 - uint转换成十六进制字符串&二进制的data打印成十六进制字符串

时间:2024-06-20 21:54:10浏览次数:12  
标签:std 十六进制 string upper text hex value 字符串 data

1. 关键词

关键字:

C++ 数据格式化 字符串处理 std::string int hex 跨平台

应用场景:

  • int 型的数据打印成十六进制字符串
  • 二进制的data打印成十六进制字符串。

2. strfmt.h

#pragma once

#include <string>
#include <cstdint>
#include <sstream>
#include <iomanip>

namespace cutl
{
    /**
     * @brief Format data to a hex string.
     *
     * @param data the data to be formatted.
     * @param len the length of the data.
     * @param upper whether to use upper case or lower case for hex characters, default is upper case.
     * @param separator the separator between each pair of hex characters, default is space.
     * @return std::string the formatted string.
     */
    std::string to_hex(const uint8_t *data, size_t len, bool upper = true, char separator = ' ');
    /**
     * @brief Format a uint8_t value to a hex string.
     *
     * @param value the value to be formatted.
     * @param upper whether to use upper case or lower case for hex characters, default is upper case.
     * @param prefix the prefix of the formatted string, default is empty.
     * @return std::string the formatted string.
     */
    std::string to_hex(uint8_t value, bool upper = true, const std::string &prefix = "");
    /**
     * @brief Format a uint16_t value to a hex string.
     *
     * @param value the value to be formatted.
     * @param upper whether to use upper case or lower case for hex characters, default is upper case.
     * @param prefix the prefix of the formatted string, default is empty.
     * @return std::string the formatted string.
     */
    std::string to_hex(uint16_t value, bool upper = true, const std::string &prefix = "");
    /**
     * @brief Format a uint32_t value to a hex string.
     *
     * @param value the value to be formatted.
     * @param upper whether to use upper case or lower case for hex characters, default is upper case.
     * @param prefix the prefix of the formatted string, default is empty.
     * @return std::string the formatted string.
     */
    std::string to_hex(uint32_t value, bool upper = true, const std::string &prefix = "");
    /**
     * @brief Format a uint64_t value to a hex string.
     *
     * @param value the value to be formatted.
     * @param upper whether to use upper case or lower case for hex characters, default is upper case.
     * @param prefix the prefix of the formatted string, default is empty.
     * @return std::string the formatted string.
     */
    std::string to_hex(uint64_t value, bool upper = true, const std::string &prefix = "");
} // namespace cutl

3. strfmt.cpp

#include <sstream>
#include <iomanip>
#include <bitset>
#include "strfmt.h"

namespace cutl
{
    static const char HEX_CHARS_UPPER[] = "0123456789ABCDEF";
    static const char HEX_CHARS_LOWER[] = "0123456789abcdef";

    std::string to_hex(const uint8_t *data, size_t len, bool upper, char separator)
    {
        const char *hex_chars = upper ? HEX_CHARS_UPPER : HEX_CHARS_LOWER;

        std::string output;
        output.reserve(3 * len);
        for (size_t i = 0; i < len; i++)
        {
            const char temp = data[i];
            output.push_back(hex_chars[temp / 16]);
            output.push_back(hex_chars[temp % 16]);
            output.push_back(separator);
        }

        return output;
    }

    std::string to_hex(uint8_t value, bool upper, const std::string &prefix)
    {
        const char *hex_chars = upper ? HEX_CHARS_UPPER : HEX_CHARS_LOWER;
        std::string text = prefix;
        int c1 = value / 16;
        int c2 = value % 16;
        text.push_back(hex_chars[c1]);
        text.push_back(hex_chars[c2]);
        return text;
    }
    std::string to_hex(uint16_t value, bool upper, const std::string &prefix)
    {
        std::string text = prefix;
        text += to_hex((uint8_t)((value >> 8) & 0xFF), upper);
        text += to_hex((uint8_t)(value & 0xFF), upper);
        return text;
    }

    std::string to_hex(uint32_t value, bool upper, const std::string &prefix)
    {
        std::string text = prefix;
        text += to_hex((uint8_t)((value >> 24) & 0xFF), upper);
        text += to_hex((uint8_t)((value >> 16) & 0xFF), upper);
        text += to_hex((uint8_t)((value >> 8) & 0xFF), upper);
        text += to_hex((uint8_t)(value & 0xFF), upper);
        return text;
    }

    std::string to_hex(uint64_t value, bool upper, const std::string &prefix)
    {
        std::string text = prefix;
        text += to_hex((uint8_t)((value >> 56) & 0xFF), upper);
        text += to_hex((uint8_t)((value >> 48) & 0xFF), upper);
        text += to_hex((uint8_t)((value >> 40) & 0xFF), upper);
        text += to_hex((uint8_t)((value >> 32) & 0xFF), upper);
        text += to_hex((uint8_t)((value >> 24) & 0xFF), upper);
        text += to_hex((uint8_t)((value >> 16) & 0xFF), upper);
        text += to_hex((uint8_t)((value >> 8) & 0xFF), upper);
        text += to_hex((uint8_t)(value & 0xFF), upper);
        return text;
    }
} // namespace cutl

4. 测试代码

#include "common.hpp"
#include "strfmt.h"

void TestToHex()
{
    PrintSubTitle("TestToHex");

    uint8_t a = 0x0f;
    std::cout << "uint8: " << cutl::to_hex(a) << std::endl;
    uint16_t b = 0xfc;
    std::cout << "uint16: " << cutl::to_hex(b) << std::endl;
    uint32_t c = 0x1b02aefc;
    std::cout << "uint32: " << cutl::to_hex(c) << std::endl;
    uint64_t d = 0xabcdef0123456789;
    std::cout << "uint64: " << cutl::to_hex(d) << std::endl;
    uint8_t bytes[] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10};
    std::cout << "bytes: " << cutl::to_hex(bytes, 16) << std::endl;
}

5. 运行结果

---------------------------------------------TestToHex----------------------------------------------
uint8: 0F
uint16: 00FC
uint32: 1B02AEFC
uint64: ABCDEF0123456789
bytes: 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 

6. 源码地址

更多详细代码,请查看本人写的C++ 通用工具库: common_util, 本项目已开源,代码简洁,且有详细的文档和Demo。

标签:std,十六进制,string,upper,text,hex,value,字符串,data
From: https://www.cnblogs.com/luoweifu/p/18259560

相关文章

  • 函数内部返回指向字符串的指针和数组名的区别
    目录两道题目进程的内存分布结论两道题目先来看两道与内存管理有关的题目以下程序会出错吗?如果不会则输出什么?#include<stdio.h>char*func(){ char*str="HelloWorld"; returnstr;}intmain(){ char*str=func(); //程序输出HelloWorld printf("%s\n",......
  • DataOps真能“降本增效”?
    在各行各业中,越来越多的公司开始重视收集数据,并寻找创新方法来获得真实可行的商业成果,并且愿意投入大量时间和金钱来实现这一目标。据IDC称,数据和分析软件及云服务市场规模在2021年达到了900亿美元,随着企业继续对人工智能和机器学习(AI/ML)和现代数据计划进行投资,预计到2......
  • DEMO_02:随机数获取;数组集合遍历;整型与字符串转换;字符串字符遍历;数组/集合排序
    /***考核点:随机数获取;数组集合遍历;整型与字符串转换;字符串字符遍历;数组/集合排序*<p>*题目:*1.使用while循环获取20个五位数随机数并打印;*2.遍历20个数,筛选出随机数中3的倍数,并统计个数;*3.符合2的数中,找出五位数中3的倍数和位置*4.符合2的数中,把这五位数......
  • datalist 是什么?以及作用是什么?
    datalist 是HTML5中引入的一个新元素,它允许你为 <input> 元素提供一个“预定义”的选项列表。用户可以在输入时从这些选项中选择,但也可以输入不在列表中的其他值。datalist 元素与 <input> 元素一起使用,通过 <option> 元素在 datalist 中定义可用的选项。datalist......
  • 每日一道算法题 删除字符串中出现次数最少的字符
    题目删除字符串中出现次数最少的字符_牛客题霸_牛客网(nowcoder.com)C语言#include<stdio.h>#include<string.h>voidfun_2024_6_17(void){charstr[20]={0};while(scanf("%s",str)!=EOF){intalpha[26]={0};intmin=20;......
  • 0基础学C++ | 第02天 | 基础知识 | sizeof关键字 | 浮点型 | 字符型 | 转义字符 | 字
    前言  该文章是在B站学习C++,同时结合自己的理解整理的笔记,视频连接:https://www.bilibili.com/video/BV1et411b73Z/?p=8&spm_id_from=333.880.my_history.page.click 1、sizeof关键字作用:利用sizeof关键字可以统计数据类型所占用的内存大小语法:sizeof(数据类型/变量)#incl......
  • DataTrigger 数据触发器触发动画的方式及问题解决
    在WPF中通过触发器实现动画的方式很常见,这里记录一下再使用DataTrigger数据触发器触发动画的一些经验,以便备忘。一、数据触发器DataTrigger与普通的触发器Trigger区别:Trigger普通触发器<!--样式--><StyleTargetType="TextBlock"><Style.Triggers><!--这里......
  • DEMO_01:List数据存储,回调函数,集合转字符串,元素去重
    *题目:*1.构建属性结构List<DemoNode>data,根据本包的data.png中数据结构图将数据存入data中(字就是nodeName)*2.将树形结构List<DemoNode>里面的元素全部遍历出来存放到List<String>list中,输出结果转换成字符串:粉粉碎机被粉碎机粉碎了怎么办*3.将list里元素去重后......
  • WPF/C#:在DataGrid中显示选择框
    前言在使用WPF的过程中可能会经常遇到在DataGrid的最前或者最后添加一列选择框的需求,今天跟大家分享一下,在自己的项目中是如何实现的。整体实现效果如下:如果对此感兴趣,可以接下来看具体实现部分。实践假设数据库中的模型如下:publicclassPerson{publicintId......
  • linux - 字符串替换
    使用场景:部署项目的时候,需要统一修改IP地址等内容。缺点:这些命令,都缺少必要的校验功能,容易因为操作失误,会出现未替换,或者替换成空串的情况。比如说:写了好多行的sed命令,不小心删了一行代码,这种情况下,执行代码不会报错,因此很容易埋下安全隐患。推荐:要进行很复杂的替换时,还是......