C++ – 字节数组byte[]或者unsigned char[]与short的相互转换
本文作者:StubbornHuang
版权声明:本文为站长原创文章,如果转载请注明原文链接!
原文标题:C++ – 字节数组byte[]或者unsigned char[]与short的相互转换
原文链接:https://www.stubbornhuang.com/2030/
发布于:2022年03月13日 8:13:22
修改于:2022年03月12日 23:16:52

设定short型长度为2。
1 short转字节数组
short型转字节数组byte[]或者unsigned char[]
void ShortToBytes(short value, unsigned char* bytes)
{
size_t length = sizeof(short);
memset(bytes, 0, sizeof(unsigned char) * length);
bytes[0] = (unsigned char)(0xff & value);
bytes[1] = (unsigned char)((0xff00 & value) >> 8);
return;
}
2 字节数组转short
字节数组byte[]或者unsigned char[]转short型
short BytesToShort(unsigned char* bytes)
{
short value = bytes[0] & 0xFF;
value |= ((bytes[1] << 8) & 0xFF00);
return value;
}
3 使用示例
#include <iostream>
void ShortToBytes(short value, unsigned char* bytes)
{
size_t length = sizeof(short);
memset(bytes, 0, sizeof(unsigned char) * length);
bytes[0] = (unsigned char)(0xff & value);
bytes[1] = (unsigned char)((0xff00 & value) >> 8);
return;
}
short BytesToShort(unsigned char* bytes)
{
short value = bytes[0] & 0xFF;
value |= ((bytes[1] << 8) & 0xFF00);
return value;
}
int main()
{
unsigned char shortByteArray[2];
short a = 10;
ShortToBytes(a, shortByteArray);
std::cout << BytesToShort(shortByteArray) << std::endl;
return 0;
}
当前分类随机文章推荐
- C++STL容器 - std::vector构造方式与分配值方式总结 阅读291次,点赞0次
- C++ - vector存储动态指针时正确释放内存 阅读4468次,点赞0次
- C++ - 动态链接库dll为什么要使用unsigned char作为byte的内部格式 阅读222次,点赞0次
- C++ – 字节数组byte[]或者unsigned char[]与float的相互转换 阅读562次,点赞0次
- C++ - std::string与std::wstring相互转换 阅读1068次,点赞0次
- C++11/std::shared_ptr - 循环引用问题 阅读3126次,点赞0次
- C++ - 判断本机文件是否存在的方式总结 阅读2575次,点赞0次
- C++ - 将Unicode std::wstring字符串转换为Unicode std::string转义字符,类似于\uxxxx的形式 阅读683次,点赞0次
- C++ 回调函数 阅读2281次,点赞0次
- C++ - Windows和Linux系统下获取当前可执行程序的绝对路径 阅读497次,点赞0次
全站随机文章推荐
- CUDA 安装报错 could not create file "...\chrome_elf.dll" 阅读885次,点赞0次
- 资源分享 - Physically Based Rendering From Theory To Implementation (Second Edition)英文高清PDF下载 阅读1980次,点赞2次
- WordPress - 防止用户在登录页面重复点击登录按钮造成重复登录 阅读159次,点赞0次
- Duilib - 超链接文本 阅读2618次,点赞0次
- 资源分享 - Computational Geometry - Algorithms and Applications, First Edition 英文高清PDF下载 阅读1146次,点赞0次
- Visual Studio - 借助远程Linux服务器环境在Visual Studio中编写和远程调试Linux C++程序 阅读511次,点赞0次
- 资源分享 - 计算机动画算法与技术,Computer Animation - Algorithms and Techniques(Second Edition)中文版PDF下载 阅读457次,点赞0次
- 计算几何与计算机图形学必读书单整理,附下载链接! 阅读11068次,点赞15次
- Google Adsense - 从Google Adsense开通到第一个10美元我用了一年时间 阅读1571次,点赞2次
- TensorRT - 自带工具trtexec的参数使用说明 阅读2479次,点赞0次
评论
153