github.com/searKing/golang/go@v1.2.117/os/signal/cgo/write_int.cpp (about) 1 // Copyright (c) 2019 The searKing authors. All Rights Reserved. 2 // 3 // Use of this source code is governed by a MIT-style license 4 // that can be found in the LICENSE file in the root of the source 5 // tree. An additional intellectual property rights grant can be found 6 // in the file PATENTS. All contributing project authors may 7 // be found in the AUTHORS file in the root of the source tree. 8 9 //go:build cgo 10 11 #include "write_int.hpp" 12 13 namespace searking { 14 15 // C++14 16 // constexpr int BitNumInDecimal(int n) { 17 // int count = 0; 18 // do { 19 // n = n / 10; 20 // count++; 21 // } while (n > 0); 22 // return count; 23 //} 24 25 // C++11 26 constexpr int BitNumInDecimal(int n) { 27 return n == 0 ? 0 : 1 + BitNumInDecimal(n / 10); 28 } 29 30 ssize_t WriteInt(int fd, int n) { 31 unsigned int unsigned_n = n >= 0 ? n : -n; 32 // + 1 for sign 33 const auto kBits = BitNumInDecimal(unsigned_n) + 1; 34 char nums[kBits]; 35 for (auto i = 0; i < kBits; i++) { 36 nums[i] = 0; 37 } 38 39 // push bits by a reverse order 40 int idx = 0; 41 do { 42 nums[idx] = '0' + (unsigned_n % 10); 43 idx++; 44 unsigned_n /= 10; 45 } while (unsigned_n && idx < sizeof(nums) / sizeof(nums[0])); 46 if (n < 0 && idx < sizeof(nums) / sizeof(nums[0])) { 47 nums[idx] = '-'; 48 idx++; 49 } 50 51 // reverse as a stack 52 auto cnt = idx; 53 for (auto i = 0; i < cnt / 2; i++) { 54 nums[i] = nums[i] ^ nums[cnt - 1 - i]; 55 nums[cnt - 1 - i] = nums[i] ^ nums[cnt - 1 - i]; 56 nums[i] = nums[i] ^ nums[cnt - 1 - i]; 57 } 58 return write(fd, nums, cnt); 59 } 60 } // namespace searking