首页 \ 问答 \ 将int值转换为3字节数组(反之亦然)(Converting int value into 3 byte array (and vice versa))

将int值转换为3字节数组(反之亦然)(Converting int value into 3 byte array (and vice versa))

我正在研究一个C / C ++ WinForms应用程序,它可以从硬件设备读取/写入数据。 我的应用程序有一个多选列表框,其中包含数字1 - 100000,用户最多可以选择10个数字。 当他们完成选择每个数字时,用户点击一个按钮,我的事件处理程序代码需要使用3个字节来构建固定大小(30字节)的字节数组来表示每个选定的数字,并且如果少于10个数字则填充数组选择。

作为一个例子,假设我的用户选择以下值:

17
99152
3064
52588
65536

我目前使用此代码将每个数字转换为一个字节数组:

byte[] bytes = BitConverter.GetBytes(selectedNumber);
Array.Reverse(bytes) // because BitConverter.IsLittleEndian() = true
Debug.WriteLine(BitConverter.ToString(bytes));

对于上面列出的数字,这会产生以下结果:

00-00-00-11
00-01-83-50
00-00-0B-F8
00-00-CD-6C
00-01-00-00

BitConverter给我回4个字节的数组,我只有空间使用3个字节来存储每个数字在最后的字节数组中。 我可以删除每个单独的字节数组的最重要的字节,然后像这样构建我的最终数组:

00-00-11-01-83-50-00-0B-F8-00-CD-6C-01-00-00-[padding here]

写入设备应该可以工作。 但是从设备读取数组(或类似的数组)会给我带来一些问题。 当我有一个3字节的数组,并尝试使用此代码将其转换为int ...

int i = BitConverter.ToInt32(bytes, 0);

...我得到“目标阵列不够长,无法复制集合中的所有项目。” 我想我可以在每三个字节的开始插入一个0x​​00的最重要字节,然后转换它,但有没有更好的方法来做到这一点?


I am working on a C# WinForms application that reads/writes data to/from a hardware device. My application has a multiselect listbox which contains the numbers 1 - 100000 and the user may select up to 10 numbers. When they're done selecting each number, the user clicks a button and my event handler code needs to build a fixed-size (30 bytes) byte array using 3 bytes to represent each selected number and pad the array if less than 10 numbers were selected.

As an example, suppose my user chooses the following values:

17
99152
3064
52588
65536

I'm currently using this code to convert each number into a byte array:

byte[] bytes = BitConverter.GetBytes(selectedNumber);
Array.Reverse(bytes) // because BitConverter.IsLittleEndian() = true
Debug.WriteLine(BitConverter.ToString(bytes));

For the numbers I listed above, this produces the following:

00-00-00-11
00-01-83-50
00-00-0B-F8
00-00-CD-6C
00-01-00-00

BitConverter is giving me back a 4 byte array where I only have space to use 3 bytes to store each number in the final byte array. I can drop the most significant byte of each individual byte array and then build my final array like this:

00-00-11-01-83-50-00-0B-F8-00-CD-6C-01-00-00-[padding here]

Writing that to the device should work. But reading the array (or a similar array) back from the device causes a bit of a problem for me. When I have a 3 byte array and try to convert that into an int using this code...

int i = BitConverter.ToInt32(bytes, 0);

...I get "Destination array is not long enough to copy all the items in the collection." I suppose I could insert a most significant byte of 0x00 at the beginning of every three bytes and then convert that but is there a better way to do this?


原文:https://stackoverflow.com/questions/14061448
更新时间:2022-02-24 20:02

最满意答案

你只需要检查你的itlow是否已经是items.begin() 。 如果是,地图中没有这样的元素:

itlow=items.lower_bound(key);
if(itlow->first == key)
    return itlow->second;
else if(itlow != items.begin())
    itlow--;
    return itlow->second;
else
    throw some_exception();

您可以返回迭代器,而不是抛出异常,然后如果找不到这样的元素,则可以返回items.end()

#include <iostream>
#include <map>

using namespace std;


map<int, int>::const_iterator find(const map<int, int> &items, int value)
{
    auto itlow = items.lower_bound(value);

    if(itlow->first == value)
        return itlow;
    else if(itlow != items.cbegin())
        return --itlow;
    else 
        return items.cend();

}

int main()
{
  map<int, int> items;
          items[2]=0;
  items[6]=10;
  items[15]=18;
  items[20]=22;

  auto i = find(items, 0);
  if(i != items.cend())
  {
     cout << i->second << endl;
  }
  i = find(items, 15);
  if(i != items.cend())
  {
    cout << i->second << endl;
  }
  i = find(items, 9);
  if(i != items.cend())
  {
    cout << i->second << endl;
  }
}

You just need to check if your itlow is already items.begin(). If it is, there's no such element in the map:

itlow=items.lower_bound(key);
if(itlow->first == key)
    return itlow->second;
else if(itlow != items.begin())
    itlow--;
    return itlow->second;
else
    throw some_exception();

Instead of throwing exception, you may return iterator, and then you can return items.end() if no such element is found.

#include <iostream>
#include <map>

using namespace std;


map<int, int>::const_iterator find(const map<int, int> &items, int value)
{
    auto itlow = items.lower_bound(value);

    if(itlow->first == value)
        return itlow;
    else if(itlow != items.cbegin())
        return --itlow;
    else 
        return items.cend();

}

int main()
{
  map<int, int> items;
          items[2]=0;
  items[6]=10;
  items[15]=18;
  items[20]=22;

  auto i = find(items, 0);
  if(i != items.cend())
  {
     cout << i->second << endl;
  }
  i = find(items, 15);
  if(i != items.cend())
  {
    cout << i->second << endl;
  }
  i = find(items, 9);
  if(i != items.cend())
  {
    cout << i->second << endl;
  }
}

相关问答

更多
  • getRoutes()按值返回,这意味着origine->getRoutes()返回的是一个临时值 ,它将在full-expression之后被销毁。 在此之后it变得悬空,任何取消引用都会导致UB 。 您可以使用命名变量来避免此问题。 例如 map m = origine->getRoutes(); it = m.begin(); ... 请注意,出于同样的原因,在for循环中, origine->getRoutes()被调用两次并返回两个不相关的对象。 从它们获得的迭代器 ...
  • 是的,你可以存储一个可变类型,比如boost::any或者(我的个人偏好, boost::variant ) 所以你的值类型可以定义为: typedef boost::variant value_type; 存储在map ,然后在提取值后,使用访问者概念进行处理。 Yes you can, store a variadic type, such as boost::any or (my personal preference, boost::variant) So your ...
  • 我的理解是CHAR *的equals运算符只是等于指针的内存地址。 你的理解是正确的。 最简单的方法是使用std::string作为键。 这样你就可以毫不费力地比较实际的字符串值: std::map m; PSTRUCTTYPE s = bar(); m.insert(std::make_pair("foo", s)); if(m.find("foo") != m.end()) { // works now } 请注意,如果您不总是手动删除它们 ...
  • 你只需要检查你的itlow是否已经是items.begin() 。 如果是,地图中没有这样的元素: itlow=items.lower_bound(key); if(itlow->first == key) return itlow->second; else if(itlow != items.begin()) itlow--; return itlow->second; else throw some_exception(); 您可以返回迭代器,而不是抛出异常,然后如果 ...
  • 您可以使用lower_bound()来查找所需元素之后的第一个元素,然后递减迭代器并使用equal_range()来访问与该元素匹配的所有元素: 码 #include #include int main() { std::multimap const m{{1,'x'}, {2,'g'}, {3,'n'}, {3,'m'}, {4,'z'}, {5 'a'}}; auto i = m.lower_bound(4); ...
  • 您应该按日对对象进行分组,然后再渲染它 const items = [ { day: 'Monday', band: 'Oasis' }, { day: 'Monday', band: 'Blur' }, { day: 'Monday', band: 'Blue' }, { day: 'Tuesday', band: 'REM' }, { day: 'Wednesd ...
  • 如果我理解正确,你需要一种方便的方法来确定地图有多少条目(node_id,i) ,其中node_id是固定的, i可以是任何东西。 如果这种理解是正确的,你可以利用这样一个事实:你的地图中的排序是基于std::less>定义的顺序,默认情况下是字典排序。 换句话说,node-id将用作主要排序标准,而该对的第二个元素将用作次要排序标准。 因此,您可以使用map的lower_bound和upper_bound函数来确定给定node-id的条目范围,如下所示(C ++ 11 ...
  • 您使用pair(0x00ffc468, 0x00ffbdb0)调用find 。 集合中没有这样的对,所以find返回end 。 您的代码比较char * ,它检查它们是否指向内存中的相同位置,而不是它们是否指向相同的内容。 您应该使用std::string而不是char *而不是重新发明轮子。 这是一个可能的比较函数示例,如果您坚持这样做,可以使用它: bool less( std::pair const& p1, std::pa ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)